龙空技术网

vuex之module小例

老潇 201

前言:

此刻小伙伴们对“vuex如何使用module”都比较重视,大家都想要分析一些“vuex如何使用module”的相关资讯。那么小编也在网摘上收集了一些对于“vuex如何使用module””的相关内容,希望看官们能喜欢,各位老铁们一起来学习一下吧!

说到前面, 状态管理(vuex)遇到的问题

大家在使用单一状态管理的时候,项目越大的情况下,所有状态集中到一个对象上,会显得比较臃肿。团队开发的时候,有可能会操作同一个文件,容易冲突

解决: Vuex给我们提供了一个 module,直白一点,就是可以把一个大的store,拆分开,模块化开发

代码情况

目录结构,就是普通的通过vue-cli生成出来的,创建一个store文件夹.

store/index.js

import Vue from 'vue';import Vuex from 'vuex';Vue.use(Vuex);import demo from './demo'import demo2 from './demo2'export default new Vuex.Store({ modules:{ demo, demo2 }})

store/demo.js store/demo2.js 两个代码可以一样,比较重要的是 namespaced这个字段

const state = { count:10,}const mutations = { increment(state){ state.count++ }}export default { namespaced:true, state, mutations}

namespaced 就是命名空间的意思,之前用过命名空间的同学,应该很容易明白,就是后续的操作需要加上命名空间,比如,之前提交mutations的形式是 this.$store.commit('increment') 现在需要变成 this.$store.commit('命名空间/increment')这种形式,而命名空间就是文件的名字,这里其实就是 this.$store.commit('demo/increment') this.$store.commit('demo2/increment')

这样的操作有何好处?我想大家都应该体会到了吧,团队合作开发便利,并且很好的把大的对象拆分n个。

当然,千万别忘记,在main.js里面需要引入 store/index.js 必须注入到 vue中才可以使用。往下继续看:

main.js

import Vue from 'vue'import App from './App.vue'import store from './store/'Vue.config.productionTip = falsenew Vue({ store, //这里一定要注入 render: h => h(App),}).$mount('#app')

注入进去后,在我们的 *.vue文件中就可以使用了,比如在 App.vue中使用:

App.vue

<template> <div id="app"> <div> {{$store.state.demo.count}} <br> {{$store.state.demo2.count}} </div> <button @click="handleIncrement">点击增加</button> </div></template><script>export default { name: 'app', mounted(){ console.log(this.$store); }, methods:{ handleIncrement(){ this.$store.commit('demo/increment'); this.$store.commit('demo2/increment'); } }}</script>

标签: #vuex如何使用module