在 Vue2 中使用 Vuex2 的步骤

在 Vue2 中使用 Vuex2 的步骤

1.安装 Vuex:

npm install vuex@2 --save

2.创建一个 store.js 文件,用于存放应用的状态管理逻辑:

// 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: {
    // 在这里定义异步操作,可以调用 mutations
    incrementAsync({ commit }) {
      setTimeout(() => {
        commit('increment');
      }, 1000);
    }
  },
  getters: {
    // 在这里定义获取状态的方法
    getCount: state => {
      return state.count;
    }
  }
});

3.在 main.js 文件中引入 store,并将其添加到 Vue 实例中:

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

new Vue({
  el: '#app',
  store, // 将 store 添加到 Vue 实例中
  render: h => h(App)
});

4.在组件中使用 store 的状态和方法:

<template>
    <div>
        <!-- 老写法比较繁琐 -->
        <p>Count: {{ $store.state.count }}</p>
        <p>Count: {{ $store.state.num }}-{{ num }}</p>
        <p>Double Count: {{ $store.getters.doubleCount }}</p>

        <button @click="$store.dispatch('increment')">Increment</button>
        <button @click="decrement">Decrement</button>

        <hr>
        <!-- 现在的写法 -->
        <p>Count: {{ count }}</p>
        <p>Double Count: {{ doubleCount }}</p>
        <button @click="increment">Increment</button>
        <button @click="decrement">Decrement</button>
    </div>
</template>
<script>
 import { mapState, mapGetters, mapActions } from 'vuex';
 
 export default {
   computed: {
     // 简化取state,getters
     ...mapState({
       count: state => state.count,
       num: state => state.num,
     }),
     ...mapGetters({
       doubleCount: 'doubleCount',
     }),
   },
   methods: {
     // 简化取action,mutation,建立一个对应关系
     ...mapActions({
       increment: 'increment',
       decrement: 'decrement',
     }),
   },
  };
</script>
<style>
</style>
  • 6
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值