Vuex 是什么?
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
什么是“状态管理模式”?
我们简单的把知识点联系起来,将Vuex简单比喻成一个vue组件
简单比喻:
1.store --------- 初始化数据 - 相当于组件的 data
2.getters ------- 计算 - 相当于组件的 computed
3.mutations — 相对于组件的 methods 书写同步代码
4.actions ------- 相当于组件的 methods 书写异步代码
获取方式:
1.store ----- this.$store.state.store
2.getters ----- this.$store.getters.getters
3.Vuex通过commit调用mutations ------------ this.$store.commit(“add”, 1);
4.Vuex通过dispatch调用actions ----------------- this.$store.dispatch(“asyncAdd”, 2);
举个栗子
创建 src/store/index.js
import Vue from "vue";
import Vuex from "vuex"
// 以插件形式注册到Vue中
Vue.use(Vuex)
// 创建Store实例
const store = new Vuex.Store({
// 初始化数据
// 初始化数据 - 相当于组件的 data
state: {
count: 99
},
// 计算 - 相当于组件的 computed
getters: {
doubleCount(state) {
return state.count * 2
}
},
// mutations 同步修改定义,通过commit调用
main.js // mutations - 相对于组件的 methods 书写同步代码
mutations: {
// 参数1:state 当前仓库state
// 参数2:payload 当前仓库commit调用时传递的参数
add(state, payload) {
// 同步修改
state.count += payload
}
},
// actions 异步,通过dispatch调用
// actions - 相当于组件的 methods 书写异步代码
actions: {
asyncAdd(store, data) {
// 模拟异步请求
setTimeout(() => {
// 模拟请求完成后的修改
store.commit('add', data)
}, 1000);
}
}
})
// 默认导出
export default store
注册 main.js
使用 cart.vue
<template>
<view>
<!-- 注意:$store.state.xxx 写法在小程序端的模板中不兼容 -->
<view> 全局-state {{ count }} </view>
<view> 全局计算-getters {{ doubleCount }} </view>
<button @click="hendlerAdd">mutations同步点击+1</button>
<button @click="hendlerAsyncAdd">actions异步点击+2</button>
</view>
</template>
<script>
export default {
data() {
return {};
},
computed: {
// 通过computed计算出一个新变量用于小程序模板绑定
count() {
return this.$store.state.count;
},
doubleCount() {
return this.$store.getters.doubleCount;
},
},
methods: {
hendlerAdd() {
// Vuex通过commit调用mutations
this.$store.commit("add", 1);
},
hendlerAsyncAdd() {
// Vuex通过dispatch调用actions
this.$store.dispatch("asyncAdd", 2);
},
},
};
</script>
<style>
</style>