vue–vuex详解

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

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)
}
},
data:function(){
return {
// num:5
}
}
})
new Vue({
el:"#app",
data:{
name:"dk"
},
store:myStore,
mounted:function(){
console.log(this)
}
})
</script>
</html>

当点击p标签前,chrome中显示:

点击p标签后:

可以看出:更改state的数据并显示在组件中,有几个步骤:1. 在mutations选项里,注册函数 函数里面装逻辑代码。2.在组件里,this.$store.commit(‘change’,payload) 注意:提交的函数名要一一对应 3.触发函数,state就会相应更改 4.在组件的计算属性里this.$store.state 获取你想要得到的数据

actions:既然mutations只能处理同步函数,我大js全靠‘异步回调’吃饭,怎么能没有异步,于是actions出现了…

actions和mutations的区别

1.Actions提交的是 mutations,而不是直接变更状态。也就是说,actions会通过mutations,让mutations帮他提交数据的变更。

2.Action 可以包含任意异步操作。ajax、setTimeout、setInterval不在话下   

再来看一下实例:   


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<script src="./js/vuex.js"></script>
<script src="./js/vue2.0.js"></script>
<body>
<div id="app">
<hello></hello>
</div>
</body>
<script>
Vue.use(Vuex);
var myStore = new Vuex.Store({
state:{
//存放组件之间共享的数据
name:"jjk",
age:18,
num:1
},
mutations:{
//显式的更改state里的数据
change:function(state,a){
// state.num++;
console.log(state.num += a);

},
changeAsync:function(state,a){
console.log(state.num +=a);
}