Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。Vuex 也集成到 Vue 的官方调试工具 devtools extension,提供了诸如零配置的 time-travel 调试、状态快照导入导出等高级调试功能。
vuex有四大金刚:store,actions,getters,mutations;
store:是数据对象;
getters:用法相当于vue组件里面的computed;
mutations:修改store;
actions:也可以修改store,跟mutations不一样的地方是,mutations只能同步修改store,actions可以异步;
一个简单的store.js;
import vue form 'vue';
impot vuex from 'vuex';
Vue.use(Vuex);
let store=new Vuex.Store({
state:{
count:0,
firstName:"Xie",
lastName:"Bessic"
},
getters:{
fullName: state => {
return `${state.firstName} ${state.lastName}`
}
},
actions:{
addCount({ commit, state }, num) {
commit('updataCount', num)
}
},
munations:{
updataCount(state, num) {
state.count = state.count + num;
/**
mutations里的方法只接受两个参数,第一个是state,第二个参数是要传进来的数据,文档中的说第二个参数是载荷(Payload);
在大多数情况下,载荷应该是一个对象,这样可以包含多个字段并且记录的 mutation 会更易读;
**/
},
}
})
export default store;
引入,在入口js文件
import store from XXX;
new Vue({
el: '#app',
router,
store,
components: { App },
template: '<App/>'
})
在vue组件里面引用(基础版)
const Counter = {
template: `<div>
<div> count:{{ count }}</div>
<div> count:{{ fullName}}</div>
<div @click='add'>按钮+2</div>
<div @click='addAction'>用actions</div>
</div>`,
methods:{
add(){
this.$commit('updataCount',5)
//要调用mutations的方法都用this.$commit调起,
//this.$commit第一个参数是调起的方法,第二个参数是要传给这 个mutations的参数;
//如果要传多个数据给mutations,可以传一个对象处理;如this.$commit('updataCoun', //{num:6,type:1}
},
addAction(){
this.dispatch('addCount',9)
}
},
computed: {
count () {
return this.$store.state.count
},
fullName(){
return this.$sotre.getters.fullName;
}
}
}
在vue组件里面引用(简化版)
mapState,mapMutations,mapGetters,mapActions
import {mapState,mapMutations,mapGetters,mapActions} from 'vuex';
const Counter = {
template: `<div>
<div> count:{{ count }}</div>
<div> count:{{ fullName}}</div>
<div @click='add'>按钮+2</div>
</div>`,
methods:{
...mapActions(['updataCount']),
...mapMutations(['updataCount']),
addCount(num){
this.addCount(num);
this.updateCount(num);
},
},
computed: {
...mapState([count]),
...mapGetters([fullName'']),
}
}