vuex介绍
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理数据,以相应的规则保证状态以一种可预测的方式发生变化
vuex中存什么
多个组件共享状态,才存储在vuex中
官方学习文档
准备
下载vuex包
yarn add vuex
新建一个文件夹并建一个js文件
在脚手架的环境进行操作
import Vue from 'vue'
import Vuex from 'vuex'
// 3. 注册
Vue.use(Vuex)
// 4. 实例化store对象
const store = new Vuex.Store({
//写入store核心仓库,5个核心概念
})
// 5. 导出store对象
export default store
在main.js中注入
import Vue from 'vue'
import App from './App.vue'
import store from '@/store' // 导入store对象
Vue.config.productionTip = false
new Vue({
// 6. 注入到Vue实例中(确保组件this.$store使用)
store,
render: h => h(App),
}).$mount('#app')
vuex-state数据源
定义
state: {
变量名: 初始值
}
使用
方式1: 组件内 - 直接使用
this.$store.state.变量名
组件内 - 映射使用 (推荐)
import { mapState } from 'vuex'
export default {
computed: {
// 2. 把state里变量映射到计算属性中
...mapState(['state里的变量名'])
}
}
vuex-mutations定义-同步修改
定义
mutations: {
函数名 (state, 可选值) {
// 同步修改state值代码
}
}
使用
方式1: 组件内 - 直接使用
this.$store.commit("mutations里的函数名", 具体值)
组件内 - 映射使用 (推荐)
// 1. 拿到mapMutations辅助函数
import { mapMutations } from 'vuex'
export default {
methods: {
// 2. 把mutations里方法映射到原地
...mapMutations(['mutations里的函数名'])
}
}
vuex-actions定义-异步修改
定义
actions: {
函数名 (store, 可选值) {
// 异步代码, 把结果commit给mutations给state赋值
}
}
使用
方式1: 组件内 - 直接使用
this.$store.dispatch('actions函数名', 具体值)
组件内 - 映射使用 (推荐)
// 1. 拿到mapActions辅助函数
import { mapActions } from 'vuex'
export default {
methods: {
// 2. 把actions里方法映射到原地
...mapActions(['actions里的函数名'])
}
}
vuex-getters定义-计算属性
定义
getters: {
计算属性名 (state) {
return 值给计算属性
}
}
使用
方式1: 组件内 - 直接使用
this.$store.getters.计算属性名
组件内 - 映射使用 (推荐)
// 1. 拿到mapGetters辅助函数
import { mapGetters } from 'vuex'
export default {
computed: {
// 2. 把getters里属性映射到原地
...mapGetters(['getters里的计算属性名'])
}
}
vuex-modules定义-分模块
创建modules模块对象
创建一个Moudle文件夹在里面创建js文件
const cartModule = {
state() {
return {
}
},
mutations: {
},
actions: {
},
getters: {
}
}
export default cartModule
引入到store.js文件里并注册
mport 变量名 from '路径'
注册
modules: {
模块名: 模块对象
}
分模块-影响state取值方式
- 只要分模块, state取值方式改变, 其他暂时不变
方式1: 组件内 - 直接使用
//原先语法this.$store.state.变量名
this.$store.state.模块名.变量名
方式2: 组件内 - 映射使用
//原语法 ...mapState(['state里变量名'])
...mapState({
state => state.模块名.变量名
})
或者
...mapState({
goodList(state){
return state.cart.goodList
}
})
分模块-命名空间
目的: 防止多个模块之间, mutations/actions/getters的名字冲突
在模块对象内设置namespaced: true
const 模块名 = {
namespaced: true,
state () {},
mutations: {},
actions: {},
getters: {},
modules: {}
}
state使用方式修改
直接使用
this.$store.state.模块名.变量名
辅助函数使用
...mapState("模块名", ['state变量名'])
mutations使用方式修改
直接使用
this.$store.commit("模块名/mutations里的函数名", 具体值)
辅助函数使用
...mapMutations("模块名", ['mutations里方法名'])
actions使用方式修改
直接使用
this.$store.dispatch("模块名/actions里的函数名", 具体值)
辅助函数使用
...mapActions("模块名", ['actions里方法名'])
getters使用方式修改
直接使用
this.$store.getters['模块名/计算属性名']
辅助函数使用
...mapGetters("模块名", ['getters里计算属性名'])