vuex是什么?
vuex是官方提供的一个插件,状态管理库,集中式管理项目中组件共用的数据。切记,并不是全部项目都需要vuex,如果项目很小,完全不需要vuex,如果项目很大,组件很多,数据很多,数据维护很费经,使用vuex
// state;仓库存储数据的地方
// mutations:修改state的唯一手段
// actions:处理action,可以书写自己的业务逻辑,也可以处理异步
// getters:理解为计算属性,用于简化仓库数据,让组件获取仓库的数据更加方便
*********如果项目过大,组件很多,接口也很多,数据也有很多,可以让Vuex实现模块式开发
把大仓库划分为多个小仓库
vuex基本使用(以下以模块式开发为例):
import Vue from "vue";
import Vuex from 'vuex';
// 需要使用插件一次
Vue.use(Vuex);
// 引入小仓库
import home from './home'
import search from './search'
import datail from './detail'
import shopcart from './shopcart'
import user from './user'
import trade from './trade'
// 对外暴露Store类的一个实例
export default new Vuex.Store({
// 实现vuex仓库模块式开发存储数据
modules:{
home,
search,
datail,
shopcart,
user,
trade
}
});
以home.js为例
import { reqCategoryList, reqGetBannerList , reqFloorList } from '@/api'
// home模块的小仓库
const state = {
// state中数据默认初始值别瞎写,服务器返回对象,服务器返回数组,【根据接口返回值初始化的】
categoryList: [],
// 轮播图的数据
bannerList: [],
// floor组件的数据
floorList:[]
};
// mutations是唯一修改state的地方 ,在action中是不允许修改的
const mutations = {
CATEGORYLIST(state, categoryList) {
state.categoryList = categoryList;
},
GETBANNERLIST(state, bannerList) {
state.bannerList = bannerList;
},
GETFLOORLIST(state,floorList){
state.floorList=floorList;
}
};
const actions = {
// 通过API里面的接口函数调用,向服务器发请求,获取服务器数据
async categoryList({ commit }) {
let result = await reqCategoryList();
if (result.code == 200) {
commit("CATEGORYLIST", result.data);
}
},
// 获取首页轮播图的数据 返回的是promise 等待响应的结果 因此写入async await
async getBannerList({ commit }) {
let result = await reqGetBannerList();
if (result.code == 200) {
commit('GETBANNERLIST', result.data)
}
},
async getFloorList({commit}){
let result= await reqFloorList();
if(result.code==200){
// 提交mutation
commit('GETFLOORLIST',result.data);
}
}
};
// 计算属性
const getters = {};
export default {
state,
mutations,
actions,
getters
}
在main.js入口文件中引入仓库:
// 引入仓库
import store from '@/store'
new Vue({
render: h => h(App)
// 注册仓库:组件实例的身上会多个一个属性$store属性
store
}).$mount('#app')
在组件中的使用方式
import { mapState } from "vuex";
// 组件挂载完毕:可以向服务器发请求
mounted() {
// 通知vuex发请求,获取数据,存储于仓库中
this.$store.dispatch('categoryList')
},
computed: {
...mapState({
// 注入一个参数state,其实即为大仓库的数据
categoryList: (state) => {
return state.home.categoryList;
},
}),
},