vuex
vuex相当于java中的一个公共的父类,里面有state(存放公共的属性)
基本语法:
Vue.use(Vuex);//在创建Vue实例之前
var myStore = new Vuex.Store({
state:{
//存放组件之间共享的数据
name:"jjk"
},
mutations:{
//显式的更改state里的数据
},
getters:{
//获取数据的方法
},
actions:{
//
}
});
new Vue({
el:"#app",
data:{
name:"dk"
},
store:myStore,
mounted:function(){
console.log(this)//控制台
}
})
----
Vue.use(Vuex);
var myStore = new Vuex.Store({
state:{
//存放组件之间共享的数据
name:"jjk"
},
mutations:{
//显式的更改state里的数据
},
getters:{
//过滤state数据
},
actions:{
//
}
});
Vue.component('hello',{
template:"<p>{{name}}</p>",
computed: {
name:function(){
return this.$store.state.name
}
},
mounted:function(){
console.log(this)
}
})
new Vue({
el:"#app",
data:{
name:"dk"
},
store:myStore,
mounted:function(){
console.log(this)
}
})
输出jjk
-----
Vue.use(Vuex);
var myStore = new Vuex.Store({
state:{
//存放组件之间共享的数据
name:"jjk",
age:18
},
mutations:{
//显式的更改state里的数据
},
getters:{
getAge:function(state){
return state.age;
}
},
actions:{
//
}
});
Vue.component('hello',{
template:"<p>姓名:{{name}} 年龄:{{age}}</p>",
computed: {
name:function(){
return this.$store.state.name
},
age:function(){
return this.$store.getters.getAge
}
},
mounted:function(){
console.log(this)
}
})
new Vue({
el:"#app",
data:{
name:"dk"
},
store:myStore,
mounted:function(){
console.log(this)
}
})
输出 姓名:jjk 年龄:18
----
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);
}
},
getters:{
getAge:function(state){
return state.age;
}
},
actions:{
//
}
});
Vue.component('hello',{
template:"<p @click='changeNum'>姓名:{{name}} 年龄:{{age}} 次数:{{num}}</p>",
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)
}
})
输出 姓名:jjk 年龄:18 次数:1
点击p标签后输出 姓名:jjk 年龄:18 次数:11
可以看出:更改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不在话下

浙公网安备 33010602011771号