脚本宝典收集整理的这篇文章主要介绍了【vuex+vue-cli】vue-cli项目中vuex的使用,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
vuex/index
Store实例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,mutationsimport actions from './actions';
import mutations from './mutations';
import getters from './getters';
import state from './state';
export default {
namespaced: true, //命名空间,自动根据模块注册的路径调整命名
state,
getters,
actions,
mutations
};
state.js
vuex stateexport default {
count: 0
}
getter.js
export default {
/*getters可以帮我们从state中进一步过滤我们需要的一些状态条件*/
getCount: (state) => {
return state.count;
}
}
mutation_tyPE.js
命名变量//这个js文件里面只是一些变量,把action和mutation文件里面相同变量名的链接起来
export const VUEX_test = 'increment';
// 一般使用的是大写来命名变量,因为尤大也是这么做 2333
actions.js
import * as types from './mutation_type';
export default {
addCount({commit}){
commit(types.VUEX_TEST);
}
};
mutations.js
import * as types from './mutation_type';//引入变量
export default {
//types.VUEX_TEST 代表接受哪个actions的commit 也就是上面引入变量的作用
[types.VUEX_TEST](state){
state.count++
}
};
main.js
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>
以上是脚本宝典为你收集整理的【vuex+vue-cli】vue-cli项目中vuex的使用全部内容,希望文章能够帮你解决【vuex+vue-cli】vue-cli项目中vuex的使用所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。