最简单的Vuex示例

学习Vuex,弄个最简单的例子备忘一下,mapGetters, mapActions, mapMutations, state都用到了。

1.老规矩,vue-cli脚手架来一下

vue init webpack-simple testvue

找到main.js,改一下内容

import Vue from 'vue'
import App from './App'
import Vuex from 'vuex'
import store from './vuex/store'
Vue.use(Vuex)
new Vue({
el: '#app',
store,
render: h => h(App)
})

2.在src下创建 src/components/count.vue文件,内容 如下

<template>
<div>
<h2>{{msg}}</h2>
<hr/>
<h3>{{$store.state.a.count}}</h3>
</div>
</template>
<script>
import store from '../vuex/store'
export default{
data(){
return{
msg:'Hello Vuex',

}
},
store
}
</script>

3.在src/App.vue中的代码如下,这里button刻意用了不同的表达式测试,另外count1还加入了模块moduleA,所以会表达成 store.state.a.count1的样式,如果不用模块,就要表达成 s t o r e . s t a t e . a . c o u n t 1 的 样 式 , 如 果 不 用 模 块 , 就 要 表 达 成 store.state.count1。用 countval引入了上面的count.vue文件。另外,这里add用了表达式$store.commit(‘add’,10),所以在后面的store.js中无需在actions中commit了。

<template>
<div>
<p>App vue</p>
<p>{{msg}}</p>
<button @click="$store.commit('add',10)">+</button>
<button @click="reduce">-</button>
<button @click="addAction">action+</button>
<button @click="reduceAction">action-</button>
<p>this is a getters count value: {{$store.getters.count}}</p>
<p>this is a state count value: {{$store.state.a.count1}}</p>

<countval></countval>
</div>
</template>

<script>
import countval from './components/count'
import {mapState, mapGetters, mapActions, mapMutations} from 'vuex' //use commit

export default {
  name: 'app',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App'
    }
  },

computed:{
...mapGetters(['count']),
...mapState(['count1'])
},

methods: {
...mapMutations([
'add',
'reduce'
]),
...mapActions([
'addAction',
'reduceAction'
])
},
  
components: {
countval,
}
}
</script>

4.创建src/vuex/store.js文件,内容如下,

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const state ={
count:0,
count1:0
}

const mutations = {
add(state,n){
state.count+=n;
state.count1 += 1;
},
reduce(state){ //step1 needed
state.count-=1;
state.count1 -= 1;
}
}

const actions ={
reduce:({commit}) => commit('reduce'),
addAction(context){
//注意这里对reduce 进行了一次操作,会额外引发getters操作+100
setTimeout(()=>{context.commit('reduce')},3000);
console.log('我比reduce提前执行');
context.commit('add',10)
},
reduceAction({commit}){
commit('reduce')
}
}

const getters={ //对count的属性进行操作,只要count有任何变化,结果都会+100
count:function(state){
return state.count +=100;
}
}

const moduleA={
state,mutations,getters,actions
}

const store = new Vuex.Store({
//不用moduleA的话,就用下面这行
//state, mutations, actions, getters
//用moduleA的话,就是
modules:{a:moduleA} //也就是count.vue中的$store.state.a.count
})

export default store

5.如果上述文件都正确的话,在cmd中敲入npm run dev字样,就会出现以下界面

最简单的Vuex示例_vue.js

点击Action+一次,会出现

最简单的Vuex示例_vue.js_02

再点击Action-一次,会出现

最简单的Vuex示例_vuejs_03

好了,慢慢玩吧!