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

vue3 store用法

作者:◆丶依然如风   发布日期:2026-07-16   浏览:56

// store.js

// 引入 Vue 和 Vuex
import { createApp } from 'vue';
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
  }
});

// 挂载 store 到根组件
const app = createApp(App);
app.use(store);
app.mount('#app');

// 在组件中使用 store
export default {
  computed: {
    // 从 store 中获取 count
    count() {
      return this.$store.getters.count;
    }
  },
  methods: {
    // 触发 store 中的 action 来增加 count
    increment() {
      this.$store.dispatch('increment');
    }
  }
};

解释说明:

  1. 引入依赖

    • createApp 是 Vue 3 的创建应用实例的方法。
    • createStore 是 Vuex 4 的创建 store 实例的方法。
  2. 创建 Store

    • state:存储应用的状态,这里是 count
    • mutations:定义改变状态的方法,这里是 increment 方法。
    • actions:用于提交 mutation 或执行异步操作,这里是简单的 increment 方法。
    • getters:用于从 state 中派生出一些状态,这里是直接返回 count
  3. 挂载 Store

    • 使用 app.use(store) 将 store 挂载到 Vue 应用实例上。
  4. 在组件中使用 Store

    • 使用 computed 属性来获取 store 中的 count
    • 使用 methods 中的 increment 方法来触发 store 中的 increment action。

上一篇:vue3安装scss

下一篇: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 中文站