一步秒懂 Vuex

Vuex 是什么?

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。

什么是“状态管理模式”?

我们简单的把知识点联系起来,将Vuex简单比喻成一个vue组件

简单比喻:

1.store --------- 初始化数据 - 相当于组件的 data
2.getters ------- 计算 - 相当于组件的 computed
3.mutations — 相对于组件的 methods 书写同步代码
4.actions ------- 相当于组件的 methods 书写异步代码

获取方式:

1.store ----- this.$store.state.store
2.getters ----- this.$store.getters.getters
3.Vuex通过commit调用mutations ------------ this.$store.commit(“add”, 1);
4.Vuex通过dispatch调用actions ----------------- this.$store.dispatch(“asyncAdd”, 2);
  举个栗子

创建 src/store/index.js

import Vue from "vue";
import Vuex from "vuex"

// 以插件形式注册到Vue中
Vue.use(Vuex)

// 创建Store实例
const store = new Vuex.Store({
    // 初始化数据
    // 初始化数据 - 相当于组件的 data
    state: {
        count: 99
    },
    // 计算 - 相当于组件的 computed
    getters: {
        doubleCount(state) {
            return state.count * 2
        }
    },
    // mutations 同步修改定义,通过commit调用
main.js    // mutations - 相对于组件的 methods 书写同步代码
    mutations: {
        // 参数1:state     当前仓库state
        // 参数2:payload   当前仓库commit调用时传递的参数
        add(state, payload) {
            // 同步修改 
            state.count += payload
        }
    },
    // actions 异步,通过dispatch调用
    // actions - 相当于组件的 methods 书写异步代码
    actions: {
        asyncAdd(store, data) {
            // 模拟异步请求
            setTimeout(() => {
                // 模拟请求完成后的修改
                store.commit('add', data)
            }, 1000);
        }
    }
})

// 默认导出
export default store

注册 main.js

main.js

使用 cart.vue

<template>
  <view>
    <!-- 注意:$store.state.xxx 写法在小程序端的模板中不兼容 -->
    <view> 全局-state {{ count }} </view>
    <view> 全局计算-getters {{ doubleCount }} </view>
    <button @click="hendlerAdd">mutations同步点击+1</button>
    <button @click="hendlerAsyncAdd">actions异步点击+2</button>
  </view>
</template>

<script>
export default {
  data() {
    return {};
  },
  computed: {
    // 通过computed计算出一个新变量用于小程序模板绑定
    count() {
      return this.$store.state.count;
    },
    doubleCount() {
      return this.$store.getters.doubleCount;
    },
  },
  methods: {
    hendlerAdd() {
      // Vuex通过commit调用mutations
      this.$store.commit("add", 1);
    },
    hendlerAsyncAdd() {
      // Vuex通过dispatch调用actions
      this.$store.dispatch("asyncAdd", 2);
    },
  },
};
</script>

<style>
</style>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值