什么是Vuex
Vuex是Vue配套的公共数据管理工具,我们可以将共享的数据保存到vuex中,方便整个程序中的任何组件都可以获取和修改vuex中保存的公共数据。
下载地址,vuex.js在dist目录中
注意:导入Vuex之前必须先导入Vue
Vuex的使用
1.创建Vuex对象
// 创建vuex对象
const store = new Vuex.Store({
//这里的state就相当于组件中的data,就是专门用于保存共享数据的
state: {
msg:"hello world"
}
})
2.在祖先组件中添加store的key保存Vuex对象
Vue.component("grandfather", {
template: '#grandfather',
//只要在祖先组件中保存了Vuex对象,那么祖先组件和所有的后代组件以使用Vuex中保存的共享数据
store: store,
//爸爸组件
components: {
"father": {
template: "#father",
//儿子组件
components: {
"son": {
template: "#son"
}
}
}
}
});
3.使用Vuex中保存的数据
<div id="app">
<grandfather></grandfather>
</div>
<template id="grandfather">
<div>
// 使用格式必须如下,msg前面部分固定
<p>{{this.$store.state.msg}}</p>
<father></father>
</div>
</template>
修改共享数据的方法(mutations属性)
不推荐直接修改共享数据:如果多个组件都修改了共享的数据,那么后期数据发生了错误,我们如果需要取调试错误,就需要把每一个修改了共享数据的组件都检查一遍,非常低效。
mutations中定义方法
const store = new Vuex.Store({
//用于保存共享数据
state: {
count:0
},
//用于保存修改共享数据的方法
mutations:{
mAdd(state){
state.count = statcount+1;
},
mSub(state){
state.count = statcount-1;
}
}
})
注意:在执行mutations中定义的方法的时候,系统会自动给这些方法传递一个state参数,state中就保存了共享的数据
方法的调用
Vue.component("grandfather", {
template: '#grandfather',
store: store,
components: {
"father": {
template: "#father",
methods:{
add(){
//不建议使用 this.$store.state.count=this.$store.state.count+1;
this.$store.commit('mAdd');
}
}
}
}
});
getters属性
专门用于定义计算属性的,作用类似于computed计算属性
计算属性是基于它们的依赖进行缓存的:计算结果缓存起来,只要计算值不变,再次调用不会再次执行函数,会直接返回计算结果
const store = new Vuex.Store({
//用于保存共享数据
state: {
msg:"hello world"
},
//用于保存修改共享数据的方法
mutations:{
},
getters:{
formart(state){
return state.msg+"你好";
}
}
});
调用方法:
{{this.$store.getters.formart}}