安装
npm install vuex --save;
目录搭建
-store
-store.js
使用
// store.js
import vue from 'vue'
import vuex from 'vuex'
vue.use(vuex)
export const store = new vuex.Store({
state:{
name:'abc'
},
// 获取数据
getters:{
name : (state) =>{
var changeName = state.name + 'aaa'
return changeName ;
}
},
// 触发事件,修改数据
mutations:{
changeName:(state,newValue)=>{
state.name = newValue
}
},
// 异步; 对mutations的提交进行处理
actions:{
changeNameAction:(context,newValue)=>{
setTimeout(()=>{
context.commit('changeName',newValue)
},2000)
}
}
})
使用store
this.$store.state.name;
this.$store.getters.name; //...mapGetters(['name'])
this.$store.commit('changeName',''tom') // 调用mutations中的方法
this.$store.dispatch('changeName',''tom') // 调用actions中的方法 等价 ...mapActions(['changeNameAction'])
import {mapGetters,mapMutations,mapActions} from 'vuex'
...mapGetters(['name'])
...mapMutations(['changeName'])
...mapActions(['changeNameAction']) // 无参数 将this.changeNameAction映射为`this.$store.commit('changeNameAction')
...mapActions({change: 'changeNameAction') // 有参数 使用: this.change('bbb') 将this.change映射为`this.$store.commit('changeNameAction')