Vue2向Vue3过度Vuex核心概念actions

目录


1 核心概念 - actions

state是存放数据的,mutations是同步更新数据 (便于监测数据的变化, 更新视图等, 方便于调试工具查看变化),

actions则负责进行异步操作

说明:mutations必须是同步的

需求: 一秒钟之后, 要给一个数 去修改state

1.定义actions

js 复制代码
mutations: {
  changeCount (state, newCount) {
    state.count = newCount
  }
}


actions: {
  setAsyncCount (context, num) {
    // 一秒后, 给一个数, 去修改 num
    setTimeout(() => {
      context.commit('changeCount', num)
    }, 1000)
  }
},

2.组件中通过dispatch调用

js 复制代码
setAsyncCount () {
  this.$store.dispatch('setAsyncCount', 666)
}

2 辅助函数 -mapActions

1.目标:掌握辅助函数 mapActions,映射方法

mapActions 是把位于 actions中的方法提取了出来,映射到组件methods中

Son2.vue

js 复制代码
import { mapActions } from 'vuex'
methods: {
   ...mapActions(['changeCountAction'])
}

//mapActions映射的代码 本质上是以下代码的写法
//methods: {
//  changeCountAction (n) {
//    this.$store.dispatch('changeCountAction', n)
//  },
//}

直接通过 this.方法 就可以调用

vue 复制代码
<button @click="changeCountAction(200)">+异步</button>
相关推荐
科研邪修法4 小时前
PDF新增页面文字与文本批注怎么区分?以双版本培训讲义为例
前端·css·pdf
武昌库里写JAVA4 小时前
SpringBoot+Vue 项目介绍
java·javascript·git·sql·ai
Lanwarf-前端开发5 小时前
Vue3 + Canvas/WebGL 雷达扫描可视化实战:PPI、RHI、VOL、SVOL 四种模式原理与实现
前端·javascript·vue.js·webgl
FRing036 小时前
vue3干货总结2(vue3生命周期、父子通信、模版引用、provide和inject)
开发语言·前端·vue.js·vue3
锋行天下8 小时前
langgraph 全栈项目(三)
前端·人工智能·后端
YIAN8 小时前
从 LangChain 到 DeepAgents:手把手拆解 createAgent、Middleware 与复杂 Agent
javascript·langchain·deepseek
锋行天下9 小时前
langgraph 全栈项目(二)
前端·人工智能·后端
冬夜Zis9 小时前
顺着作用域链和 outer 指针,一次性看懂闭包底层逻辑
javascript
Ceelog10 小时前
Mac 上怎么找出并安全清理旧的 node_modules?(实测 304 个占 66.3 GB)
javascript