随笔 - 4  文章 - 0  评论 - 0  阅读 - 1925

学习记录 vuex 五大核心概念

VueX 是一个专门为 Vue.js 应用设计的状态管理构架,统一管理和维护各个vue组件的可变化状态(你可以理解成 vue 组件里的某些 data )。

Vuex有五个核心概念:

state, getters, mutations, actions, modules。

1. state:vuex的基本数据,用来存储变量

2. geeter:从基本数据(state)派生的数据,相当于state的计算属性

3. mutation:提交更新数据的方法,必须是同步的(如果需要异步使用action)。每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)。

4. action:和mutation的功能大致相同,不同之处在于 ==》1. Action 提交的是 mutation,而不是直接变更状态。 2. Action 可以包含任意异步操作。

5. modules:模块化vuex,可以让每一个模块拥有自己的state、mutation、action、getters,使得结构非常清晰,方便管理。

 

回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数,提交载荷作为第二个参数。

Vuex的用法:

新建vue项目testApp  -> 在testApp中建store文件 -> store文件下又有modules文件夹和getter.js 和 index.js -> store文件下建user.js
在项目的main.js中引入 import store from ‘./store’

在store文件下的index.js中引入

import Vue from 'vue'
import Vuex from 'vuex'
import user from './modules/user'
import global from './modules/global'
import getters from './getters'

Vue.use(Vuex)

const store = new Vuex.Store({
  modules: {
    user
  },
  getters
})

export default store

在store文件下的getters.js中引入

const getters = {
  self: state => state.user.self,
  token: state => state.user.token,
  currentCommunity: (state, getters) => {
    let cid = getters.currentCommunityId
    return getters.communities.filter(item => {
      return item.communityId === cid
    })
  }
}

export default getters


在modules文件下的user.js写代码
const user = {
     state:{
          self: null,
          token: '',
      },
      mutations:{
          SET_SELF: (state, self) => {
               state.self = self
           },
           SET_TOKEN: (state, token) => {
               state.token = token
           }
      },
      actions:{
           login ({ commit }, res) {
                commit('SET_SELF', res.self)
                commit('SET_TOKEN', res.token
      }       
}
export default user                

使用下面这两种方法存储数据:

dispatch:异步操作,写法: this.$store.dispatch(‘mutations方法名’,值)
commit:同步操作,写法:this.$store.commit(‘mutations方法名’,值)
posted on   zhangyuxin219  阅读(77)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示