vue是一个面向数据,只有一个层:view,在数据传给客户端之前,计算其相关的属性,应该是什么样子,前面有个mapState([])远程加载数据,加载的是一个静态的数据,如果想获取动态的数据,就要用到 getters 。官方建议在getter和computed不推荐使用箭头函数。
这个例子依旧沿用了之前vuex学习---简介的模板
1.首先在store.js中
一开始会在页面上显示 :104 常量值4+ getters中的100 ;点击加 会104+ 100+3 ,变成207 ;点击减207+100-1 = 306 ,依次如此。
1 import Vue from 'vue'
2 import Vuex from 'vuex'
3
4 //使用vuex模块
5 Vue.use(Vuex);
6
7 //声明静态常量为4
8 const state = {
9 count : 4
10 };
11
12 //定义一个方法,在vue中,唯一的定义状态的方法就是提交一个mutations,
13 //而且导出时,只要导出mutations即可,
14 //当使用时,也仅仅只要使用统一的 $store.commit('event') event是事件名称。
15 const mutations = {
16 add(state,n){
17 state.count +=n.a;
18 },
19 sub(state){
20 state.count--;
21 }
22 };
23 //定义getters 不推荐使用箭头函数
24 const getters = {
25 count:function(state){
26 return state.count +=100
27 }
28 };
29
30 //导出一个模块
31 export default new Vuex.Store({
32 state,
33 mutations,
34 getters
35 })
2. 在App.vue中
<template>
<div id="app">
<div id="appaaa">
<h1>这是vuex的示例</h1>
<p>调用仓库常量 {{$store.state.count}}</p>
<!-- <p>组件内部count{{count111}}</p> -->
<p>组件内部count{{count}}</p>
<p>
<button @click = "$store.commit('add',{a:3})">加</button>
<button @click = "sub">减</button>
</p>
</div>
</div>
</template>
<script>
//引入mapGetters
import {mapState,mapMutations,mapGetters} from 'vuex'
export default {
name:'app',
data(){
return {
}
},
computed:{
/*
...mapState
对于getters这段代码是不需要的,这个是为了
<button @click = "$store.commit('add',{a:3})">加</button>*/
...mapState([
"count"
]),
// count(){
// return this.$store.getters.count;
// }
...mapGetters([
"count"
])
},
methods:mapMutations([
'add',
'sub'
])
}
</script>
<style>
</style>
来源:https://www.cnblogs.com/wjylca/p/7055662.html