vuex的五个属性
1.state – 存放状态
2.getters – state的计算属性
3.mutations – 更改状态的逻辑,同步操作
4.actions – 提交mutation,异步操作
5.mudules – 将store模块化
使用
const store = new Vuex.Store({ state: { info: {"name":"我是vuex","id":1,"Name":"王二麻子"} } })
1、在组件中可以使用来获取vuex中公共的state的值
this.$store.state.info.Name;//"王二麻子"
也可以使用以下来取值
import { mapState, mapGetters,mapActions, mapMutations } from "vuex";
mounted() {
console.log(mapState);
},
computed: {
...mapGetters(["getStudentLength"])
},
methods:{
...mapMutations(['sub']),
...mapActions(['addA'])
}
2、在组件中修改vuex中的state的值
//第一种方法:在组件中
<button type="button" @click="newName"></button>
methods: {
newName: function() {
this.$store.commit('newName', this.newValue)//通过commit调取vuex中的newName事件来修改
}
}
//第二种方法:在组件中
methods:{
...mapMutation(['add','add2'])//这样就能直接创建store中定义在mutations的方法了。
this.newName(this.newValue)
}
//在vuex中
mutations: {
newName(state,msg) {
state.info.Name = msg;
}
}
3、通过actions来修改vuex中state的值
方法一、
...mapActions(['saveDbSource'])//先引入actions里的方法
this.saveDbSource//使用
方法二、
this.$store.dispatch('saveDbSource', this.DbSource);//通过dispatch调用actions里的saveDbSource
vuex中
actions:{
saveDbSource(context,num){ //context:上下文对象,这里你可以理解称store本身。
context.commit('newName',num)//通过调用mutations里是newName方法来改变vuex中的state。
//这边就是调用mutations的方法,这样才能异步,不要直接调用state中的数据。
}
}