Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

vuex之module小记 #13

Open
itstrive opened this issue May 28, 2019 · 0 comments
Open

vuex之module小记 #13

itstrive opened this issue May 28, 2019 · 0 comments
Labels
article small article js About Js something Vue VueJs

Comments

@itstrive
Copy link
Owner

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

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

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


代码情况

|-src/
  |-assets/
  |-components/
  |-store
    |-demo.js
    |-demo2.js
    |-index.js
  |-App.vue
  |-main.js

目录结构,就是普通的通过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 = false

new 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>
@itstrive itstrive added article small article js About Js something Vue VueJs labels Jun 11, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
article small article js About Js something Vue VueJs
Projects
None yet
Development

No branches or pull requests

1 participant