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

vue store

作者:血之メ狂霸   发布日期:2025-02-17   浏览:60

// src/store/index.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: {
    increment ({ commit }) {
      commit('increment');
    }
  },
  getters: {
    count: state => state.count
  }
});

// 在 main.js 中引入 store
// import Vue from 'vue';
// import App from './App.vue';
// import store from './store';

// new Vue({
//   store,
//   render: h => h(App)
// }).$mount('#app');

// 使用示例:
// this.$store.commit('increment'); // 直接调用 mutation 修改状态
// this.$store.dispatch('increment'); // 调用 action 触发 mutation 修改状态
// console.log(this.$store.getters.count); // 获取当前状态

解释说明:

  1. Vuex Store 创建

    • state:存储应用的状态,例如 count
    • mutations:定义了如何修改状态的方法。increment 方法会将 count 增加 1。
    • actions:用于处理异步操作或复杂的业务逻辑。increment 动作会触发 commit 来调用对应的 mutation。
    • getters:用于获取状态的计算属性。这里我们定义了一个 count getter 来获取 state.count
  2. 在组件中使用

    • 可以通过 this.$store.commit('increment') 直接调用 mutation 修改状态。
    • 也可以通过 this.$store.dispatch('increment') 调用 action 触发 mutation 修改状态。
    • 使用 this.$store.getters.count 获取当前的状态值。
  3. 引入和挂载

    • main.js 中引入并挂载 store 到 Vue 实例中,这样所有的组件都可以访问到 store。

上一篇:vue3 defineexpose

下一篇:vue3+ts

大家都在看

vue.config.js configu

node.js vue

vue查看版本

vue等待几秒

vue3 setup computed

vue screenfull

vue json.stringify

vue 遍历list

typescript vue

vue 复选框

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

Laravel 中文站