状态管理模式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 @   陈彦斌  阅读(6)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
历史上的今天:
2019-08-06 Md5工具类
点击右上角即可分享
微信分享提示