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

vue3使用vuex

作者:醉眼看苍生   发布日期:2026-05-14   浏览:54

// store.js

import { createStore } from 'vuex';

// 创建一个新的 store 实例。
const store = createStore({
  state() {
    return {
      count: 0
    };
  },
  mutations: {
    increment(state) {
      state.count++;
    }
  },
  actions: {
    increment({ commit }) {
      commit('increment');
    }
  },
  getters: {
    count: state => state.count
  }
});

export default store;

// main.js

import { createApp } from 'vue';
import App from './App.vue';
import store from './store';

const app = createApp(App);

app.use(store);

app.mount('#app');

// 在组件中使用

<template>
  <div>
    <p>{{ count }}</p>
    <button @click="increment">Increment</button>
  </div>
</template>

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

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

解释说明:

  1. 创建 Vuex Store

    • createStore 函数用于创建一个新的 Vuex store 实例。
    • state 是一个函数,返回应用的状态对象。这里我们定义了一个 count 属性,初始值为 0。
    • mutations 是同步事务处理函数,用于修改状态。这里定义了一个 increment 方法,每次调用时将 count 加 1。
    • actions 类似于 mutations,但可以包含异步操作。这里定义了一个 increment action,它会调用 mutation 来更新状态。
    • getters 类似于 Vue 的计算属性,用于从 state 中派生出一些状态。
  2. 在主应用中使用 Vuex

    • main.js 中,通过 app.use(store) 将 Vuex store 注入到 Vue 应用中。
  3. 在组件中使用 Vuex

    • 使用 mapStatemapActions 辅助函数来简化对 Vuex state 和 actions 的访问。
    • mapState(['count'])count 映射到组件的计算属性中。
    • mapActions(['increment'])increment 映射到组件的方法中,这样可以直接在模板中调用 increment 方法来触发 Vuex action。

这样就可以在 Vue 3 应用中使用 Vuex 来管理全局状态了。

上一篇:vue data

下一篇:vue3创建项目的命令

大家都在看

vue.js devtools用法

three.js vue

vue js for循环

vue.min.js 本地引入

vue.js 3

highlight.js vue

vue.config.js 配置

vue.config.js 配置代理

vue.config.js devserv

vue.config.js configu

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

Laravel 中文站