vuex中为什么要使用模块化
- 在Vuex中应用的所有需要共享和被修改的数据源都存放在state对象中,当应用较为复杂,需要共享的数据较多时,state对象以及store对象都会变得很臃肿,不利于代码维护。并且大多应用都会根据业务分为不同的功能模块,很多情况下不同模块之间的数据交互并不密切,如果我们能将store也分割为不同模块,每个模块管理不同的数据,会使数据管理起来更加结构清晰,方便管理。 那么为了解决以上的问题,Vuex允许我们将store分割成模块。每个模块拥有自己的state、mutation、action、getter并且可以嵌套子模块。
下载vuex
npm add vuex@3
src下新建store文件夹
在store文件夹下新建index.js文件
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
//创建vuex实例对象
export default new Vuex.Store({
modules:{
}
})
在store文件夹下新建modules文件夹
在modules文件夹下新建模块user.js
export default{
namespaced:true, //开启命名空间
state:()=>{
return{
count:100
}
},
mutations:{
},
getters:{
}
}
在store文件下的index.js文件中引入模块
import userModule from './modules/user'
export default new Vuex.Store({
modules:{
"my-user":userModule
}
})
在main.js文件中引入store
import store from './store'
new Vue({
store,
render:h=>(App)
}).$mount('#app')
那么我们如何知道vuex有没有下载成功呢? 可以在App.vue中打印this.$store
export default {
created(){
console.log(this.$store)
}
}
使用方式
映射函数
首先在组件中通过import 导入映射函数,然后挂载就行
<template>
<div>
{{count}}
</div>
</template>
<script>
import {mapState} from 'vuex'
computed:{
...mapState('my-user',['count'])
}
<script/>