Vuex 是 Vue 配套的公共管理工具,他可以把一些共享的数据,保存到vuex中,
方便程序中的任何组件获取或修改我们的公共数据;
Vuex 是为了保存 组件之间共享数据而诞生的,如果组件之间有需要共享的数据,可以直接挂载到
vuex中,不必通过父子之间传值,如果组件的数据不需要共享,此时这些不需要共享的私有数据,就不要放在vuex中,
只有需要共享的数据,才有权放到vuex中,组件中内部私有数据,放在data中即可,props data
vuex 的区别
结论:vuex是一个全局共享的储存区域,相当于一个仓库 store
Vuex 创建store
export default new Vuex.Store({
state: { //**可以把state 想象成组件中的data 专门用来存储数据的**
count :0
},
//组件获取store中的state中的数据,v-model=" this.$store.state.count "(this可以省略)
mutations: {
increment(state){
state.count++
}
},
//注意,要操作 store 中的 state 的值,只能通过调用 mutations 提供的方法,才能操作对应的数据,
//不推荐直接操作 state 中的数据,万一导致数据的紊乱,在大项目中,不能快速定位到错误的原因,
//因为每个组件都有操作数据的方法
组件中调用 mutations 中的方法:
this.$store.commit("increment")
案例:
创建state数据,和mutations 里面的方法
export default new Vuex.Store({
state: {
count:5
},
mutations: {
increment(){ //传参和不传参的两种写法
this.state.count++
},
subtraction(state){
state.count--
}
},
actions: {
}
})
组件调用store的数据和方法
<template>
<div id="counter">
<input type="button" value="减" @click="subtraction">
<input type="text" v-model="$store.state.count">
<input type="button" value="加" @click="add">
</div>
</template>
<script>
export default {
name:"counter",
methods:{
add(){
this.$store.commit('increment')
},
subtraction(){
this.$store.commit("subtraction")
}
}
}
</script>
上述就可以实现通过store进行加减操作
mutations 的函数列表传参数的问题
还是上面那个例子
subtraction(state,c){
state.count-=c
}
//调用 和 子组件向父组件传参数有点类似,mutations中函数传参最多两个,(state ,其他)
subtraction(){
this.$store.commit("subtraction",5)
}
虽然只能传两个,但是最后一个可以传对象
mutations: {
increment(state, obj) {
this.state.count += (obj.a + obj.b)
}
},
调用
add(){
this.$store.commit('increment',{a:5,b:7})
},
这样每次加的就是5+7 = 12,只是告诉这样一个思想,可以传多种数据类型
getters,只负责对外提供数据,不负责修改数据,如果要修改,去找mutations
getters:{
opt(state){
return "当前的值是"+state.count
}
}
//使用数据
<h2>{{$store.getters.opt}}</h2>
//看起来和过滤器有点像,都没有修改源数据,都是把原数据做了一层包装,提供给了调用者,
//其次 getters 和computed 比较像,只要 state 中的数据发生变化,正好getters 也引入了这个数据,
//立马也会触发getters 的重新求值