1、Vuex的理解:
Vuex是为Vue.js 应用程序开发的状态管理模式,集中式存储管理所有组件的状态。
可理解为对要共享的data,进行集中式的管理。
核心:store仓库,包含着应用中大部分的状态
基本对象:
state:存储状态(变量)
getters:对数据获取之前的再次编译,可以理解为state的计算属性。我们在组件中使用 $sotre.getters.fun()
motations:修改状态,同步的,在组件中使用$store.commit('',params)。可以理解为组件中的自定义事件。
actions:异步操作。在组件中使用是$store.dispath(''),提交的是motations。
modules:store的子模块,每个模块有自己的state、getter、motation、action。
2、Vuex的使用
- 安装依赖
yarn add vuex
或者
npm install -save vuex
- 导入工程
入口组件<App/>中,绑定store
import Vue from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store";
Vue.config.productionTip = false;
new Vue({
router,
store,
render: h => h(App)
}).$mount("#app");
导入vuex并创建Store对象(store.ts文件)
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
//状态管理(集中管理需要共享的data)
export default new Vuex.Store({
//存储状态(变量)
state: {
count: 0
},
//修改状态,同步的,在组件中使用$store.commit('',params)
mutations: {
mutationsAddCount(state, n = 0) {
return (state.count += n);
},
mutationsReduceCount(state, n = 0) {
return (state.count -= n);
}
},
//异步操作。在组件中使用是$store.dispath('')
actions: {
actionsAddCount(context, n = 0) {
console.log(context);
return context.commit("mutationsAddCount", n);
},
actionsReduceCount({ commit }, n = 0) {
return commit("mutationsReduceCount", n);
}
},
getters: {
getterCount(state) {
return (state.count += 5);
}
}
});
引用Store对象(*.vue文件中)
<template>
<div class="hello">
<h1>{{ msg }}</h1>
<h3>{{ $store.state.count }}</h3>
<div>
<button @click="handleAddClick(10)">增加</button>
<button @click="handleReduceClick(10)">减少</button>
</div>
<div>异步操作</div>
<div>
<button @click="handleActionsAdd(10)">异步增加</button>
<button @click="handleActionsReduce(10)">异步减少</button>
</div>
</div>
</template>
<script lang="ts">
import { Component, Prop, Vue } from "vue-property-decorator";
@Component
export default class HelloWorld extends Vue {
@Prop() private msg!: string;
handleAddClick(n: Number) {
this.$store.commit("mutationsAddCount", n);
}
handleReduceClick(n: Number) {
this.$store.commit("mutationsReduceCount", n);
}
handleActionsAdd(n: Number) {
this.$store.dispatch("actionsAddCount", n);
}
handleActionsReduce(n: Number) {
this.$store.dispatch("actionsReduceCount", n);
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
</style>