vue–vuex详解

2020-06-14 06:14:26易采站长站整理

},
getters:{
getAge:function(state){
return state.age;
}
},
actions:{
        //设置延时
add:function(context,value){
setTimeout(function(){
           //提交事件
context.commit('changeAsync',value);
},1000)

}
}
});

Vue.component('hello',{
template:`
<div>
<p @click='changeNum'>姓名:{{name}} 年龄:{{age}} 次数:{{num}}</p>
<button @click='changeNumAnsyc'>change</button>
</div>`,
computed: {
name:function(){
return this.$store.state.name
},
age:function(){
return this.$store.getters.getAge
},
num:function(){
return this.$store.state.num
}
},
mounted:function(){
console.log(this)
},
methods: {
changeNum: function(){
//在组件里提交
// this.num++;
this.$store.commit('change',10)
},
        //在组件里派发事件 当点击按钮时,changeNumAnsyc触发-->actions里的add函数被触发-->mutations里的changeAsync函数触发

changeNumAnsyc:function(){
this.$store.dispatch('add', 5);
}
},
data:function(){
return {
// num:5
}
}
})
new Vue({
el:"#app",
data:{
name:"dk"
},
store:myStore,
mounted:function(){
console.log(this)
}
})
</script>
</html>

点击按钮一秒后,chrome中显示:

  

先整明白 context dispatch是什么东西:

context:context是与 store 实例具有相同方法和属性的对象。可以通过

context.state
context.getters
来获取 state 和 getters。

dispatch:翻译为‘派发、派遣’的意思,触发事件时,dispatch就会通知actions(跟commit一样一样的)参数跟commit也是一样的。

action的大体流程:

1.在actions选项里添加函数(异步)并提交到对应的函数(在mutation选项里)中context.commit(‘changeAsync’,value);   


actions:{
add:function(context,value){
setTimeout(function(){
context.commit('changeAsync',value);
},1000)

}
}

2.在组件里:changeNumAnsyc:function(){this.$store.dispatch(‘add’, 5);} 将dispatch“指向”actions选项里的函数