npm install vuex --save
....../vuex/store.js:
import Vuex from 'vuex';
import Vue from 'vue';
Vue.use(vuex);
const state = { count:1}
const mutations = {
add(state){
state.count++;
},
reduce(state){
state.count--;
}
}
export default new Vuex.Store({ state,mutations });
Count.vue
<template>
<div>
<h2>{{msg}}<h2>
<h3>{{$store.state.count}}</h3>
<p>
<button @click="$store.commit('add')">+</button>
<button @click="$store.commit('reduce')">-</button>
</p>
</div>
</template>
<script>
import store from '@/vuex/store.js'
export default{
data(){
return {
msg:"hello vuex"
}
},
store
}
</script>
//可以写成下面这样,然后在上面直接用{{count}}
computed:{
count(){
return this.$store.state.count;
}
}
//还可以这样,在Count.vue中,import { mapState } from 'vuex'; 注意一定要有花括号
computed:mapState({
count:state=>state.count;
})
//还可以这样,在Count.vue中,import {mapState} from 'vuex';
computed:mapState(['state'])
MapState:
add(state,param){
state.count+=param;
}
<button @click="$store.commit('add',10)"></button>
//还可以这样
import { mapState,mapMutations } from 'vuex'
methods:mapMutations(['add','reduce'])
...@click='reduce'...
Getters:
需要使用扩展运算符
Actions:
actions区别于mutations是,actions里的函数是可以异步执行的。
1.
2.
3.
Modules:
1.
2.