状态管理模式Vuex

Vuex

  • 定义

    • Vuex 是集中式存储管理应用的所有组件的状态(数据)
  • 作用

    • 可实现任意组件之间的通讯
  • 特点

    • 当不同的组件需要对同一个状态进行读写时,或者复用的状态较多
    • 能够保持数据和页面是响应式的
    • 便于开发和后期数据维护

安装

cnpm install --save vuex

创建 /store/index.js 文件

// 创建 /store/index.js 文件
​
import Vue from 'vue'    //引入Vue
import Vuex from 'vuex'  //引入Vuex
Vue.use(Vuex)            //应用
​
export default new Vuex.Store({
  actions:{},            //接受用户的事件
  mutations:{},          //操作state中的数据
  state:{},              //存放共享的数据
})
// main.js
​
import store from './store/index.js'
​
new Vue({
  el:"#app",
  render: h => h(App),
  store:store
})
  • 实现对 store 数据的 count 累加和累减
    • 读取 store 的state
<h1>当前的计数:{{ $store.state.count }}</h1>
  • 操作 store 的state
methods: {
// 累加
  add() {
    this.$store.commit("ADD", this.sum);        //同步操作
    // this.$store.dispatch("add", this.sum);   //异步操作
  },
// 累减
  reduce() {
    this.$store.commit("REDUCE", this.sum);      //同步操作
    // this.$store.dispatch("reduce", this.sum); //异步操作
  },
},
  • store 配置 actions 和 mutations
//接受用户的事件
actions: {
  add(context, value) {
    context.commit('ADD', value);
  },
  reduce(context, value) {
    setTimeout(() => {
      context.commit('REDUCE', value);
    }, 1000);
  },
},
//操作state中的数据
mutations: {
  ADD(state, value) {
    state.count += value;
  },
  REDUCE(state, value) {
    state.count -= value;
  },
},
  • 注意

    • actions 能够提供 dispatch 方法实现异步操作
    • mutations 必须是同步函数
    • state 只能通过 mutations 配置的方法去修改
posted @ 2023-08-06 22:27  陈彦斌  阅读(9)  评论(0)    收藏  举报