Vuex 3使用总结

版本问题

截止博客发布前,Vuex 拥有 3.x 和 4.x 版本。

本文总结的是与 Vue 2 匹配的 Vuex 3 的使用。

更多操作请参考官方文档:https://v3.vuex.vuejs.org/

与 Vue 3 匹配的 Vuex 4 的文档: https://vuex.vuejs.org/

状态管理模式

写过 vue 项目的程序员应该都知道父子组件传参的方式,通过子组件的 props 参数,和 $emit 来触发事件。

但是当遇到多个组件共享状态时,传参的方法对于多层嵌套的组件将会非常繁琐,并且对于兄弟组件间的状态传递无能为力,甚至会导致无法维护的代码。

基于此,把组件的共享状态抽取出来,以一个全局单例模式管理,vuex 就产生了。

在这里插入图片描述

安装使用

Vue 2 的脚手架项目,安装 3.6.2版本。

npm install vuex@3.6.2 --save

在 src 目录下新建 store 文件夹,在该目录下新建 index.js

index.js

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const state = {
   
  count: 1
}

const getters = {
   

}

const mutations = {
   
  add(state, n) {
   
    state.count += n
  },
  reduce(state) {
   
    state.count--
  }
}

const actions = {
   

}

export default new Vuex.Store({
   
  state,
  getters,
  mutations,
  actions
})

入口文件引入

main.js

import store from './store'

new Vue({
   
  el: '#app',
  store,
  components: {
   
    App
  },
  template: '<App/>'
})

简单示例

通过 commit 提交 mutation 中的方法修改 state。

组件代码

<template>
  <div>
    <el-button @click="$store.commit('add', 1)">add
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值