操做步骤
- 在src目录中建立文件夹 vuex,并建立以下文件.

import Vue from 'vue';
import Vuex from 'vuex'; // 引入对应模块
import status from './moudules/status/index';//引入vue模块
Vue.use(Vuex);//安装Vue插件 vuex
export default new Vuex.Store({
modules:{ //将 store 分割成模块
status
}
});//导出vuex实例
-
vuex/moudule/status/index
vuex模块,每一个模块有本身的 state,getters,actions,mutations
import actions from './actions';
import mutations from './mutations';
import getters from './getters';
import state from './state';
export default {
namespaced: true, //命名空间,自动根据模块注册的路径调整命名
state,
getters,
actions,
mutations
};
export default {
count: 0
}
export default {
/*getters能够帮咱们从state中进一步过滤咱们须要的一些状态条件*/
getCount: (state) => {
return state.count;
}
}
//这个js文件里面只是一些变量,把action和mutation文件里面相同变量名的连接起来
export const VUEX_TEST = 'increment';
// 通常使用的是大写来命名变量,由于尤大也是这么作 2333
import * as types from './mutation_type';
export default {
addCount({commit}){
commit(types.VUEX_TEST);
}
};
import * as types from './mutation_type';//引入变量
export default {
//types.VUEX_TEST 表明接受哪一个actions的commit 也就是上面引入变量的做用
[types.VUEX_TEST](state){
state.count++
}
};
使用
import Vue from 'vue'
import App from './App'
import MintUI from 'mint-ui'
import router from './router'
import store from './vuex';//引入文件
Vue.config.productionTip = false;//设置为 false 以阻止 vue 在启动时生成生产提示。
Vue.use(MintUI);
new Vue({
el: '#app',
router,
store,
components: { App },
template: '<App/>'
})
<template>
<div id="app">
<img src="./assets/logo.png">
<div>
<p>{{getCount}}</p>
<mt-button type="primary" v-on:click="add">add</mt-button>
</div>
<router-view/>
</div>
</template>
<script>
import axios from "axios";
import { mapGetters, mapActions, mapState } from "vuex";
export default {
name: "App",
data: ()=> {
return {
selected: 1
};
},
watch: {
selected: function(val) {
console.log(val);
}
},
computed:{
...mapGetters({
'getCount': 'status/getCount'
})
},
mounted:function(){
console.log(this.$store.state.status.count)
},
methods:{
add(){
console.log(this.$store.dispatch('status/addCount'));
}
}
};
</script>