Vuex原理图
1. 概念
在Vue中实现集中式状态(数据)的管理的一个Vue插件,对vue应用中多个组件的共享状态进行集中式的管理(读/写),也是一种组件间通信的方式,且适用于任意组件间通信
2. 何时使用
多个组件需要共享数据时;
或者
由于项目体积比较大,你向服务器发请求的接口过多,服务器返回的数据也会很多,如果还用以前的方式存储数据,导致vuex中的state数据格式比较复杂。采用vuex模块式管理数据
本项目中home、search等四个组件需要模块化管理,
创建如图所示目录:
3. 搭建Vuex环境
//准备actions对象———响应组件中用户的动作
const actions = {}
// 准备mutations——用于操作数据(state)
const mutations = {}
// 准备state——用于存储数据
const state = {}
//当state中的数据需要经过加工后再使用时,可以使用getters加工
const getters = {}
在home/index.js中:
import { reqCategoryList, reqGetBannerList } from '@/api'
// home模块的小仓库
const state = {
// state中数据默认初始值要根据接口返回值写,服务器返回对象还是数组等其他形式
categoryList: [],
}
const mutations = {
CATEGORYLIST(state, categoryList) {
state.categoryList = categoryList
},
}
const actions = {
// 通过API里面的接口函数调用,向服务器发请求,获取服务器的数据
async categoryList({ commit }) {
let result = await reqCategoryList()
if (result.code == 200) {
commit('CATEGORYLIST', result.data)
}
},
}
const getters = {}
export default {
state,
mutations,
actions:actions,
getters
}
在store/index.js(汇总模块化组件):
// 引入Vue核心库
import Vue from 'vue'
// 引入vuex
import Vuex from 'vuex'
// 应用Vuex插件
Vue.use(Vuex)
// 引入小仓库
import home from './home'
import search from './search'
// 创建并暴露store
export default new Vuex.Store({
// 实现Vuex仓库模块式开发存储数据
modules: {
home,
search
}
})
4. 使用
4.1 在main.js引入store
......
//引入store
import store from './store'
......
//创建vm
new Vue({
render: h => h(App),
// 注册路由: 下面的写法是KV一致,省略了V【router小写】
// 注册路由信息:这里配置router的时候,组件身上都有$route,$router属性
router,
store,
}).$mount('#app')
4.2 mapXxx方法使用
mapState方法:用于帮助我们映射state中的数据为计算属性
......
// 组件挂载完毕,向服务器发请求
mounted() {
// 通知vuex发请求,获取数据,存储于仓库中
this.$store.dispatch("categoryList");
},
computed: {
...mapState({
// 右侧需要的是一个函数,当使用这个计算属性的时候,右侧函数会立即执行一次
// 参数state是大仓库中的数据
categoryList: (state) => state.home.categoryList, //返回了home状态下的所有数据
}),
},
......
若没有网络请求或其他业务逻辑,组件中也可以越过actions,即不写dispatch,直接编写commit
4.3 组件遍历渲染数据
<div
class="item"
//遍历得到一级数据
v-for="(c1, index) in categoryList"
:key="c1.categoryId"
:class="{ cur: currentIndex == index }"
>
<h3 @mouseenter="changeIndex(index)">
<a
:data-categoryName="c1.categoryName"
:data-category1Id="c1.categoryId"
>{{ c1.categoryName }}</a
>
</h3>
<!-- 二级、三级分类 -->
<div
class="item-list clearfix"
:style="{ display: currentIndex == index ? 'block' : 'none' }"
>
<div
class="subitem"
v-for="c2 in c1.categoryChild"
:key="c2.categoryId"
>
<dl class="fore">
<dt>
<a
:data-categoryName="c2.categoryName"
:data-category2Id="c2.categoryId"
>{{ c2.categoryName }}</a
>
</dt>
<dd>
<em v-for="c3 in c2.categoryChild" :key="c3.categoryId">
<a
:data-categoryName="c3.categoryName"
:data-category3Id="c3.categoryId"
>{{ c3.categoryName }}</a
>
</em>
</dd>
</dl>
</div>
</div>
</div>