vuex的使用

129 阅读1分钟

1、vuex是什么

Vuex是专门为Vuejs应用程序设计的状态管理工具。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。

2、vuex的结构

vuex的结构

3、vuex的组成

1)state

state是存储的单一状态,是存储的基本数据。 在组件中可以直接使用$store.state.数据(不建议直接使用)

在computed监听使用 this.$store.state.数据

2)Getters

getters是store的计算属性,对state的加工,是派生出来的数据。就像computed计算属性一样,getter返回的值会根据它的依赖被缓存起来,且只有当它的依赖值发生改变才会被重新计算。 在组件使用:$sotre.getters.方法

3)Mutations mutations提交更改数据,使用store.commit方法更改state存储的状态。

在 组 件 中 使 用 $store.commit('')

4)Actions actions像一个装饰器,提交mutation,而不是直接变更状态。

在组件中使用是$store.dispath('')

5)Module Module是store分割的模块,每个模块拥有自己的state、getters、mutations、actions。

const moduleA = {

state: { ... },

mutations: { ... },

actions: { ... },

getters: { ... }

}

const moduleB = {

state: { ... },

mutations: { ... },

actions: { ... }

}

const store = new Vuex.Store({

modules: {

a: moduleA,

b: moduleB

}

})

store.state.a // -> moduleA 的状态 store.state.b // -> moduleB 的状态

4、vuex的运行机制

在组件用this.$store.dispath来调用action中的方法,在actions中通过commit来调用mutation中的方法,在mutations中改变state中的数据,只要数据发生变化就会响应到组件上

5、vuex的使用

import Vuex from 'vuex';

Vue.use(Vuex); // 1. vue的插件机制,安装vuex

let store = new Vuex.Store({ // 2.实例化store,调用install方法

state,
getters,
modules,
mutations,
actions

});

new Vue({ // 3.注入store, 挂载vue实例

store,
render: h=>h(app)

}).$mount('#app');