问小白 wenxiaobai
资讯
历史
科技
环境与自然
成长
游戏
财经
文学与艺术
美食
健康
家居
文化
情感
汽车
三农
军事
旅行
运动
教育
生活
星座命理

Vue:Vuex-Store使用指南

创作时间:
作者:
@小白创作中心

Vue:Vuex-Store使用指南

引用
CSDN
1.
https://blog.csdn.net/ChinaDragon10/article/details/141143969

一、简介

Vuex 是什么

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。Vuex 也集成到 Vue 的官方调试工具 devtools extension,提供了诸如零配置的 time-travel 调试、状态快照导入导出等高级调试功能。

什么是“状态管理模式”?

让我们从一个简单的 Vue 计数应用开始:

new Vue({
  // state
  data () {
    return {
      count: 0
    }
  },
  // view
  template: `
    <div>{{ count }}</div>
  `,
  // actions
  methods: {
    increment () {
      this.count++
    }
  }
})

这个状态自管理应用包含以下几个部分:

  • state,驱动应用的数据源;
  • view,以声明方式将 state 映射到视图;
  • actions,响应在 view 上的用户输入导致的状态变化。

以下是一个表示“单向数据流”理念的简单示意:

但是,当我们的应用遇到多个组件共享状态时,单向数据流的简洁性很容易被破坏:

  • 多个视图依赖于同一状态。
  • 来自不同视图的行为需要变更同一状态。

对于问题一,传参的方法对于多层嵌套的组件将会非常繁琐,并且对于兄弟组件间的状态传递无能为力。
对于问题二,我们经常会采用父子组件直接引用或者通过事件来变更和同步状态的多份拷贝。以上的这些模式非常脆弱,通常会导致无法维护的代码。

因此,我们为什么不把组件的共享状态抽取出来,以一个全局单例模式管理呢?在这种模式下,我们的组件树构成了一个巨大的“视图”,不管在树的哪个位置,任何组件都能获取状态或者触发行为!

通过定义和隔离状态管理中的各种概念并通过强制规则维持视图和状态间的独立性,我们的代码将会变得更结构化且易维护。这就是 Vuex 背后的基本思想,借鉴了 Flux、Redux 和 The Elm Architecture。与其他模式不同的是,Vuex 是专门为 Vue.js 设计的状态管理库,以利用 Vue.js 的细粒度数据响应机制来进行高效的状态更新。

二、什么情况下我应该使用 Vuex?

Vuex 可以帮助我们管理共享状态,并附带了更多的概念和框架。这需要对短期和长期效益进行权衡。如果您不打算开发大型单页应用,使用 Vuex 可能是繁琐冗余的。确实是如此——如果您的应用够简单,您最好不要使用 Vuex。一个简单的store 模式就足够您所需了。但是,如果您需要构建一个中大型单页应用,您很可能会考虑如何更好地在组件外部管理状态,Vuex 将会成为自然而然的选择。

三、安装

直接下载 / CDN 引用

https://unpkg.com/vuex
https://unpkg.com/,提供了基于 NPM 的 CDN 链接。以上的链接会一直指向 NPM 上发布的最新版本。您也可以通过 https://unpkg.com/vuex@2.0.0 这样的方式指定特定的版本。

在 Vue 之后引入 vuex 会进行自动安装:

<script src="/path/to/vue.js"></script>
<script src="/path/to/vuex.js"></script>

NPM

npm install vuex --save

Yarn

yarn add vuex

在一个模块化的打包系统中,您必须显式地通过 Vue.use() 来安装 Vuex:

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

四、最简单的 Store(Vuex 记数应用)实例

TestVue2项目结构图

安装 vuex @3.1.0

npm install vuex@3.1.0

安装成功后,查看package.json文件

创建一个 store

安装 Vuex 之后,让我们来创建一个 store。创建过程直截了当——仅需要提供一个初始 state 对象和一些 mutation:

store文件夹里index.js文件代码

import Vue from 'vue'
import Vuex from 'vuex'
// 全局
Vue.use(Vuex)
// https://www.jb51.net/javascript/297247rzd.htm
//  https://blog.csdn.net/weixin_44904953/article/details/129159961
// export default new Vuex.Store({
const store = new Vuex.Store({
    namespaced: true,
    state: {
        count: 0,
    },
    mutations: {
        increment(state) {
            state.count++
        },
        decrement: state => state.count--,
        
        getCount(state){
            return state.count
        },
    },
    actions: {
        // 异步任务 store.dispatch
        tryactions(context, val) { //第一个参数是context固定不变,第二个是自定义参数
            setTimeout(() => {
                context.commit('increment') //调用mutations中的方法修改state中的数据
            }, val);
        },
    },
    
    getters: {
        
    },
})
export default store;

现在,你可以通过 store.state 来获取状态对象,以及通过 store.commit 方法触发状态变更:

store.commit('increment')
console.log(store.state.count) // -> 1

注入store

为了在 Vue 组件中访问 this.$store property,你需要为 Vue 实例提供创建好的 store。Vuex 提供了一个从根组件向所有子组件,以 store 选项的方式“注入”该 store 的机制:

在store文件里index.js里使用了Vue.use(Vuex),接下来在main.js将index.js导入

main.js文件代码

import Vue from 'vue'
import App from './App.vue'
// 将 Vuex Store 注入到应用中
import store from './store'
import router from './router'
Vue.config.productionTip = false
// Vue.prototype.$store = store
// https://www.jb51.net/javascript/297247rzd.htm
// 如果使用 ES6,你也可以以 ES6 对象的 property 简写 (用在对象某个 property 的 key 和被传入的变量同名时):
new Vue({
    router,
    store,
    render: h => h(App),
}).$mount('#app')
// 使用 ES2015 语法
// new Vue({
// 	router: router,
// 	store: store,
// 	render: h => h(App),
// }).$mount('#app')

再次强调,我们通过提交mutation的方式,而非直接改变 store.state.count,是因为我们想要更明确地追踪到状态的变化。这个简单的约定能够让你的意图更加明显,这样你在阅读代码的时候能更容易地解读应用内部的状态改变。此外,这样也让我们有机会去实现一些能记录每次状态改变,保存状态快照的调试工具。有了它,我们甚至可以实现如时间穿梭般的调试体验。

由于 store 中的状态是响应式的,在组件中调用 store 中的状态简单到仅需要在计算属性中返回即可。触发变化也仅仅是在组件的 methods 中提交 mutation。

创建两个vue文件

teststore1.vue代码

<template>
    <div>
        <h1>store 1 数量:{{this.$store.state.count}}</h1>
        <!-- <h1>getComputedCount 数量:{{getComputedCount}}</h1> -->
        <h1>mapState 数量:{{count}}</h1>
        <button @click="increment">+</button>
        <button @click="decrement">-</button>
        </br>
        <button @click="doactions">点击两秒后数量自动加1</button>
        <br />
        <br />
        <p>
            <button v-on:click="getCount">获取localCount最新值</button>
            获取到的数量:{{localCount}}
        </p>
        <br />
        <br />
        <button @click="openTest2Page">打开test2页面</button>
    </div>
</template>
<script>
    import {
        mapState
    } from 'vuex'
    export default {
        name: 'teststore1',
        data() {
            return {
                localCount: 0,
            }
        },
        computed: {
            ...mapState([
                'count',
            ]), //推荐这种方式
        },
        
        // watch: {
        // 	count: {
        // 		handler(newVal, oldVal) {
        // 			console.log(`teststore1 watch 新的值: ${newVal} , 旧的值: ${oldVal}`)
        // 		},
        
        // 	}
        // },
        
        created() {
            console.log("teststore1 执行了 created ")
        },
        
        activated() {
            console.log("teststore1 执行了 activated ")
        },
        
        mounted() {
            console.log("teststore1 执行了 mounted ", this.$store)
        },
        
        beforeUpdate() {
            console.log("teststore1 执行了 beforeUpdate ")
        },
        
        updated() {
            console.log("teststore1 执行了 updated ")
        },
        
        beforeDestroy() {
            console.log("teststore1 执行了 beforeDestroy ")
        },
        
        destroyed() {
            console.log("teststore1 执行了 beforeDestroy ")
        },
        
        methods: {
            increment() {
                this.$store.commit('increment')
            },
            decrement() {
                this.$store.commit('decrement')
            },
            // // 异步任务 store.dispatch	
            doactions() {
                this.$store.dispatch('tryactions', 2000)
            },
            getCount() {
                this.localCount = this.$store.state.count
                console.log("执行了 getCount this.localCount = ", this.localCount)
            },
            
            openTest2Page(){
                this.$router.push('/teststore2')
            },
        }
    }
</script>
<style>
    button {
        margin-left: 1.25rem;
        margin-top: 1.0rem;
    }
</style>

teststore2.vue代码

<template>
    <div>
        <!-- <h1>store 2 数量:{{this.$store.state.count}}</h1> -->
        <h1>store 2 数量:{{count}}</h1>
        <button @click="increment">+</button>
        <button @click="decrement">-</button>
        <button @click="goBack">返回到上个页面</button>
    </div>
</template>
<script>
    import {
        mapState
    } from 'vuex'
    export default {
        name: 'teststore2',
        data() {
            return {
                mCount: 0,
            }
        },
        
        created() {
            console.log("teststore2 执行了 created ")
        },
        
        activated() {
            console.log("teststore2 执行了 activated ")
        },
        
        mounted() {
            console.log("teststore2 执行了 mounted ", this.$store)
        },
        
        beforeUpdate() {
            console.log("teststore2 执行了 beforeUpdate ")
        },
        
        updated() {
            console.log("teststore2 执行了 updated ")
        },
        
        beforeDestroy() {
            console.log("teststore2 执行了 beforeDestroy ")
        },
        
        destroyed() {
            console.log("teststore2 执行了 beforeDestroy ")
        },
        
        computed: {
            ...mapState([
                'count',
            ]),
        },
        mounted() {
            console.log("teststore2 执行了 mounted ",this.$store)
        },
        methods: {
            increment() {
                this.$store.commit('increment')
            },
            decrement() {
                this.$store.commit('decrement')
            },
            
            goBack(){
                this.$router.replace('/teststore1')
            }
        }
    }
</script>
<style>
    button {
        margin-left: 1.25rem;
    }
</style>

五、启动TestVue2项目

TestVue2使用了vue-router,可参考vue-router使用指南

在终端里输入下面命令:

提醒:因为电脑里node版本问题,前面加了NODE_OPTIONS=–openssl-legacy-provider

NODE_OPTIONS=--openssl-legacy-provider npm run serve

六、效果图

home.vue页面

teststore1.vue页面

teststore2.vue页面

点击返回到上个页面(teststore2.vue)

七、TestVue2项目源码

点击查看TestVue2源码

© 2023 北京元石科技有限公司 ◎ 京公网安备 11010802042949号