vuex
vuex
vuex是官方提供的一个插件 状态管理库 集中式管理项目中组件公用的数据 并不是所有的的项目都需要vuex 项目小不需要 项目大 组件多 数据多 数据维护很费劲 state mutations actions getters modules 基本使用
- state:仓库存储数据的地方
- mutations:修改state的唯一手段
- actions:处理action 可以书写自己的业务逻辑 也可以处理异步
- getters:理解为计算属性 用于简化仓库数据 让组件获取仓库的数据更加方便
创建store文件夹 创建index.js文件
import Vue from "vue";
import Vuex from 'vuex'
// 需要使用插件一次
Vue.use(Vuex)
// 引入小仓库
import home from './home'
import search from './search'
// 对外暴露Store类的一个实例
export default new Vuex.Store({
// 实现Vuex仓库模块式开发存储数据
modules:{
home,
search }
});
在store文件夹下面创建小仓库文件夹 在小仓库中创建index.js文件
import {reqCategoryList} from '@/api/index.js'
// home 模块的小仓库
const state={
// state中数据默认初始值 别瞎写 服务返回对象 起始值就是对象 根据接口返回值初始化的
categoryList:[],
};
const mutations={
CATEGORYLIST(state,categoryList){
state.categoryList=categoryList
}
};
const actions={
// 通过API里面的接口函数调用 向服务器发请求 获取服务器的数据
async categoryList({commit}){
let result=await reqCategoryList();
// console.log(result.data);
if(result.code==200){
commit("CATEGORYLIST",result.data)
}
}
};
const getters={};
export default{
state,
mutations,
actions,
getters
}
在组件中
引入
import { mapState } from 'vuex'
data() {
return {
// 存储用户鼠标移上哪一个以及分类
currentIndex: -1
}
},
methods: {
// 鼠标进入 修改响应式数据currentIndex
changeIndex(index) {
// index鼠标移上某一个一级分类的元素的索引值
this.currentIndex = index
},
// 一级分类 移除的事件回调
leaveIndex() {
// 鼠标移除 currentIndex变为-1
this.currentIndex = -1
}
},
// 组件挂载完毕 可以向服务器发请求
mounted() {
// 通知Vuex发请求 获取数据 存储于仓库当中
this.$store.dispatch('categoryList')
},
computed: {
...mapState({
// 右侧需要的是一个函数 当使用这个计算属性的时候 右侧函数 会立即执行一次
// 注入一个参数state 其实即为大仓库中的数据
categoryList: state => state.home.categoryList
})
}