在vuex中getter至关于计算属性
1.在store.js中写上:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state:{
count:0,
},
mutations:{
changeCount:function (state,count) {
state.count=count
console.log(state.count)
},
getters: {
// 单个参数
countDouble: function(state){
return state.count * 2
},
// 两个参数
CountDoubleAndDouble: function(state, getters) {
return getters.countDouble * 2
}
}
})
2.在组件的页面写:(这里调用的方式有两种)
第一种:
<div class="add" @click="changeCount">+</div>
一个参数:{{countDouble}}
两个参数{{CountDoubleAndDouble}} <br />
</div>
data () {
return {
Acount:0,
}
},
(............重点............)
countDouble: function(){
return this.$store.getters.countDouble
},
countDoubleAndDouble: function(){
return this.$store.getters.countDoubleAndDouble
},
methods:{
changeCount(){
this.Acount++;
this.$store.commit('changeCount',this.Acount);
}
}
第二种:
import { mapGetters } from 'vuex'
...mapGetters([
'countDouble',
'CountDoubleAndDouble',
]),
不管用哪种结果都是同样的,看我的喜爱...........
我将getters属性理解为全部组件的computed属性, 也就是计算属性. vuex的官方文档也是说到能够将getter理解为store的计算属性, getters的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被从新计算。
我将mutaions理解为store中的methods, mutations对象中保存着更改数据的回调函数,该函数名官方规定叫type, 第一个参数是state, 第二参数是payload, 也就是自定义的参数.
actions 相似于 mutations,不一样在于:actions提交的是mutations而不是直接变动状态actions中能够包含异步操做, mutations中绝对不容许出现异步actions中的回调函数的第一个参数是context, 是一个与store实例具备相同属性和方法的对象
复制代码