Open itstrive opened 5 years ago
解决: 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这个字段
store/demo.js
store/demo2.js
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')
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中使用:
*.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)遇到的问题
解决: Vuex给我们提供了一个 module,直白一点,就是可以把一个大的store,拆分开,模块化开发
代码情况
目录结构,就是普通的通过vue-cli生成出来的,创建一个store文件夹.
store/index.js
store/demo.js
store/demo2.js
两个代码可以一样,比较重要的是 namespaced这个字段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
注入进去后,在我们的
*.vue
文件中就可以使用了,比如在App.vue
中使用:App.vue