作用
状态管理
安装
npm install vuex
使用
src目录中创建store文件夹,以及其下的index.js文件
//index.js文件
import Vue from 'vue';
import Vuex from 'vuex';
import home from './modules/home';
Vue.use(Vuex);
const store = new Vuex.Store({
// 存放状态
state: {
count: 0,
array: [1,2,3,4,5,6],
obj: {
child: {
name: 'lisi'
}
}
},
// 存放使用次数较多的函数,或者状态(state)层级太多后,用于简化引用。
getters: {
newArray(state, getters) {
return state.array.filter(item => item > 3);
},
name(state) { // 效果等同 this.$store.state.obj.child.name
return state.obj.child.name
}
},
// 用于修改状态(state),mutation方法常为同步方法。
mutations: {
increment(state, data) {// 其第一个参数是state,第二个是额外参数,由调用者传入
state.count += data.count;
}
},
// 常用于执行异步方法,执行完毕后调用mutations中相对应的方法变更状态(state)
actions: {
simulate(context) { // context == store,但是 context !== store
return new Promise(resolve => {
setTimeout(() => {
context.commit('increment'); // 调用mutations中的方法修改状态。
resolve(context.state.count);
}, 2000)
})
}
},
// 应用较为复杂有很多状态的时候,可以使用模块化,将状态进行分割。
modules: {
home
}
})
main.js
import store from './store/index';
new Vue({
el: '#app',
store
})
组件中如何调用
// 调用state
this.$store.state.xxx
// or
import { mapState } from 'vuex';
computed: {
...mapState(['xxx'])
}
// 调用getter
this.$store.getters.xxx
// or
import { mapGetters } from 'vuex';
computed: {
...mapGetters (['xxx'])
}
// 调用mutation
this.$store.commit('xxx');
// or
import { mapMutations } from 'vuex';
methods: {
...mapMutations (['xxx']),
fn() {
this.xxx();
}
}
// 调用action
this.$store.dispatch('xxx');
// or
import { mapActions } from 'vuex';
methods: {
...mapActions (['xxx']),
fn() {
this.xxx();
}
}