-
介绍
- 采用集中式存储管理,解决组件之间状态共享的问题。组件间的通信就不再是一层一层的传递,而是通过 store 进行通信。
-
通过仓库(vuex)管理状态。
-
快速入门。
-
安装 Vuex
npm install vuex
-
src 目录下新建一个 store.js 并配置 store
// 1、引入vue import Vue from "vue"; // 2、引入状态机vuex import Vuex from "vuex"; // 3、注册 Vue.use(Vuex); // 实例化一个Vue.store对象,暴露出去 export default new Vuex.Store({ // state用于状态管理,职能存储数据 state: { students: [ { name: "谢杰", age: 18 }, { name: "雅静", age: 20 }, { name: "希之", age: 2 }, { name: "牛牛", age: 2 }, ], }, // getters用于获取数据并做二次处理,类似于计算属性,不要直接通过state获取 getters: { newStuList(state) { return state.students.map((item) => { return { name: item.name, age: item.age * 2, }; }); }, }, mutations: {}, actions: {}, });
-
在 mian.js 中进行配置
import Vue from 'vue' import App from './App.vue' // 引入路由 import router from "./router/index.js"; // 引入状态机 import store from "@/store/store.js"; Vue.config.productionTip = false new Vue({ render: h => h(App), // 注册路由 router, // 注册状态机 store }).$mount('#app')
-
获取状态机里的数据
-
通过 this.$store 可以获取整个状态机
<template> <div> <ul> <li v-for="(stu, index) in stuList" :key="index"> name : {{ stu.name }} age : {{ stu.age }} </li> </ul> </div> </template> <script> export default { data() { return { stuList: "", }; }, mounted() { // 通过 this.$store.getters 获取修正后的数据 this.stuList = this.$store.getters.newStuList; }, }; </script> <style> </style>
-
-
修改仓库的状态 Mutation
-
更新仓库里面的数据
-
在 store.js 中设置 mutations
// 数据 state: { count: 1, }, mutations: { // 接收 2 个参数:state 为当前仓库的值,payload 为外面 commit 时传入的值 changeCount: (state) => { state.count = state.count + 1; }, },
-
在 computed 里通过 this.$store.getters 获取修正后的数据
computed:{ count(){ return this.$store.getters.getCount; } },
-
在 methods 自定义事件里 通过调用 commit 方法来触发 store.js 中所定义的 changeCount
methods: { clickHandel() { // 调用 commit 方法来触发 store.js 中所定义的 changeCount // age 作为第二个参数,对面的 payload 会接收此参数 this.$store.commit("changeCount"); }, },
注: mutations 是更新仓库的唯一途径
-
-
-
actions
-
管理异步操作,所有异步操作都通过 actions
-
使用实例
-
通过 actions 书写异步操作
// mutations是更新仓库的唯一途径 mutations: { // 接收 2 个参数:state 为当前仓库的值,payload 为外面 commit 时传入的值 changeCount: (state, payload) => { state.count += payload; }, }, actions: { // context 等价于 this.$store获取到整个状态机 // payload参数 changeCountAction(context, payload) { setTimeout(() => { // 监听changeCount context.commit("changeCount", payload); },2000); }, },
注:
1、mutations 是更新仓库的唯一途径,actions 只是管理异步操作,更新还必须通过 actions 触发 mutations 进行更新状态。
2、 actions 通过 context.commit 触发 mutations
-
组件通过 dispatch 来调用在 store.js 中的 actions
methods: { clickHandel() { // 调用 commit 方法来触发 store.js 中所定义的 changeCount // age 作为第二个参数,对面的 payload 会接收此参数 // this.$store.commit("changeCount"); // 不在是 this.$store.commit 方法来触发 store.js 中所定义的 changeCount, // 而是通过 dispatch 来调用在 store.js 中的 action this.$store.dispatch("changeCountAction",2) }, },
注:
1、之前通过 调用 commit 方法来触发 store.js 中所定义的 changeCount
例子:this.$store.commit(“changeCount”)
2、现在通过 dispatch 来调用在 store.js 中的 actions ,在通过 actions 触发 mutations
-
-
-
状态机 Vuex
最新推荐文章于 2024-04-19 15:05:39 发布