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

vue3中使用vuex

作者:稍纵即逝   发布日期:2026-07-27   浏览:118

// 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:

    • store.js 文件中,我们导入了 createStore 函数,并创建了一个新的 Vuex store 实例。这个实例包含了 statemutationsactionsgetters
  2. 注册 Vuex Store:

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

    • 在组件的模板中,我们使用 {{ count }} 来显示 state 中的 count 值。
    • 使用 @click="increment" 绑定按钮点击事件来触发 actions 中的 increment 方法。
    • 在组件的 <script> 部分,我们使用 mapStatemapActions 辅助函数将 Vuex 的 stateactions 映射到组件的 computedmethods 中。

这样,你就可以在 Vue 3 项目中成功集成并使用 Vuex 进行状态管理了。

上一篇:vue3 setup computed

下一篇:vue等待几秒

大家都在看

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 transpi

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

Laravel 中文站