介绍
Vuex 是一个用于 Vue.js 应用程序的状态管理模式 + 库。它充当应用程序中所有组件的集中存储,其规则确保状态只能以可预测的方式进行更改。
- 专门在vue中实现集中式状态(数据)管理的一个插件
- 对vue应用中多个组件的共享状态进行集中式的管理(读/写)
- 也是组件中的一种通信方式,且适用于任意组件间的通信
- 多组件共享数据
- 不属于任何组件
搭建vuex环境(项目中使用vuex)
- 安装vuex插件
npm install vuex@next --save
- 创建src/store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
// 可引入goods_create(其余)模块,使index中的代码更简洁
// import goods_create from './modules/goods_create.js'
Vue.use(Vuex) //注意使用必须在导入之后进行
export default new Vuex.Store({
// modules: [
// goods_create,
// ]
//存储数据
state: {
//下面这些可以定义在moudles下的子文件夹中,使代码更简洁,此时需要引入,例如:goods_create
skus_type: 0,//商品规格
},
getters: {
},
//存储操作数据(要修改的)
mutations: {
},
//准备anctions,用于响应组件中的动作
actions: {
}
})
- 在入口文件main.js中进行引用并挂载
// 引入vuex
import store from './store/index.js';
new Vue({
// 挂载路由
router,
store,
render: h => h(App),
}).$mount('#app')
此时vuex插件已配置完成
使用
- 直接使用1
<p>{{$store.state.skus_type}}</p>
- 直接使用2
this.$store.state.skus_type
3.mapState解构使用
// 解构vuex
import { mapState } from 'vuex';
export default {
name: "createGoods",
data() {
return {
}
},
computed: {
...mapState({
skus_type: state => state.skus_type,
}),
// 其他计算属性
},
// 测试是否vuex能够访问skus_type
mounted() {
console.log(this.skus_type);
},
}