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

vue2 store

作者:尛丸子的天真▍我学不会゜   发布日期:2025-07-10   浏览:104

// store.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

import Vue from 'vue';
import App from './App.vue';
import store from './store';

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

// 在组件中使用

<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.js:

    • 创建了一个 Vuex store 实例。
    • state 包含了应用的状态,例如 count
    • mutations 是唯一可以修改状态的地方,这里定义了 increment 方法来增加 count
    • actions 用于提交 mutation,这里也定义了 increment 方法。
    • getters 用于获取状态,这里定义了 count getter 来获取 count 的值。
  2. main.js:

    • 引入并注册了 Vuex store。
    • 创建 Vue 实例时,将 store 注入到根实例中。
  3. 组件中使用:

    • 使用 computed 计算属性来访问 store 中的 count 状态。
    • 使用 methods 定义了 increment 方法,通过 dispatch 触发 store 中的 action。

上一篇:vue2 filter

下一篇:vue卸载依赖包

大家都在看

vue.config.js configu

node.js vue

vue 图表组件

vue3watch监听多个变量

vue查看版本

vue3 reactive对象重新赋值

vue等待几秒

vue3 setup computed

vue screenfull

vue json.stringify

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

Laravel 中文站