Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

vue dispatch

作者:步崖   发布日期:2026-03-30   浏览:30

// 在 Vue 中使用 Vuex 的 dispatch 方法来触发 actions

// 首先确保你已经安装并配置好了 Vuex

// store.js
import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment(state) {
      state.count++;
    }
  },
  actions: {
    incrementAsync({ commit }) {
      return new Promise((resolve) => {
        setTimeout(() => {
          commit('increment');
          resolve();
        }, 1000);
      });
    }
  }
});

// 在组件中使用 dispatch 方法
<template>
  <div>
    <p>Count: {{ count }}</p>
    <button @click="increment">Increment</button>
    <button @click="incrementAsync">Increment Async</button>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex';

export default {
  computed: {
    ...mapState(['count'])
  },
  methods: {
    ...mapActions(['incrementAsync']),
    increment() {
      this.$store.commit('increment');
    }
  }
};
</script>

解释说明:

  1. Vuex Store:

    • state: 存储应用的状态,这里是一个简单的计数器。
    • mutations: 修改状态的唯一方式,必须是同步函数。increment 是一个简单的 mutation,它会将 count 状态加 1。
    • actions: 类似于 mutation,但可以包含异步操作。incrementAsync 是一个 action,它会在 1 秒后调用 commit 来提交 increment mutation。
  2. 组件:

    • 使用 mapStatemapActions 辅助函数来简化对 Vuex 状态和 actions 的访问。
    • increment 方法直接调用 this.$store.commit('increment') 来同步增加计数。
    • incrementAsync 方法通过 this.incrementAsync() 调用 store 中定义的异步 action。
  3. 按钮点击事件:

    • 当用户点击 "Increment" 按钮时,会立即增加计数。
    • 当用户点击 "Increment Async" 按钮时,会在 1 秒后增加计数。

希望这段代码和解释对你有帮助!

上一篇:vueconfig.js配置文件 proxy

下一篇:vue每次进入页面触发的方法

大家都在看

vue.js devtools用法

three.js vue

vue js for循环

vue.min.js 本地引入

highlight.js vue

vue.config.js 配置

vue.config.js 配置代理

vue.config.js configu

node.js vue

vue3 写法

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站