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

vue3 store

作者:呐爱淡了   发布日期:2025-09-20   浏览:54

// 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 实例,以便在 main.js 中使用
export default store;

// main.js

// 引入 Vue 和 store
import { createApp } from 'vue';
import App from './App.vue';
import store from './store';

// 创建 Vue 应用实例并挂载 store
const app = createApp(App);
app.use(store);
app.mount('#app');

// 在组件中使用 store

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

<script>
export default {
  computed: {
    count() {
      return this.$store.getters.count;
    }
  },
  methods: {
    increment() {
      this.$store.dispatch('increment');
    }
  }
};
</script>

解释说明:

  1. 创建 Store

    • 使用 createStore 创建一个新的 Vuex store 实例。
    • state:存储应用的状态,例如 count
    • mutations:定义改变状态的方法,例如 increment
    • actions:用于提交 mutation 的方法,可以包含异步操作。
    • getters:类似于计算属性,用于从 state 中派生出一些状态。
  2. 注册 Store

    • main.js 中引入并注册 store,使整个应用都可以访问 store。
  3. 在组件中使用 Store

    • 使用 computed 访问 store 中的 state。
    • 使用 methods 提交 mutation 或 dispatch action 来改变 state。

通过这种方式,你可以轻松地管理应用的状态,并确保状态的变化是可预测和可控的。

上一篇:vue跳转到新页面

下一篇:vue页面跳转

大家都在看

vue js for循环

vue.config.js 配置

vue.config.js configu

node.js vue

vue3组件传值的方式

vue 图表组件

vue3+vite+ts

vue3watch监听多个变量

vue查看版本

vue3 reactive对象重新赋值

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

Laravel 中文站