Vue进阶----Vuex的高阶用法汇总

本文深入探讨了Vuex的高级用法,包括 vuex 的模块化操作、状态管理和组件交互。通过分析`index.js`、`counter.js`和`operate.js`等文件,展示了Vuex属性和方法的不同引用方式,并在`common-operate`、`module-operate`系列组件中实践了这些概念。
摘要由CSDN通过智能技术生成

Vuex中文官网传送门
目录结构如下:
在这里插入图片描述
其中vuex相关的三个文件counts.js、 index.js、 operate.js,内容如下:
在这里插入图片描述

index.js

import Vue from 'vue'
import Vuex from 'vuex'
import counter from './counter.js'
import operate from './operate.js'
Vue.use(Vuex)

const state = {
   
  name: 'zhaoyh'
}

const getters = {
   
  getName (state) {
   
    return state.name
  }
}

const mutations = {
   
  changeName (state, payload) {
   
    state.name = `${
     state.name} ${
     payload}`
  }
}

const actions = {
   
  changeNameAsync (context, payload) {
   
    return new Promise((resolve, reject) => {
   
      setTimeout(() => {
   
        context.commit('changeName', payload)
      }, 1000)
    })
  }
}

const store = new Vuex.Store({
   
  state,
  getters,
  mutations,
  actions,
  modules: {
   
    counter,
    operate
  }
})

export default store

counter.js

// 模块内方法调用本模块内的方法和数据
const state = {
   
  counterName: 'module > counter > zhaoyh'
}
const getters = {
   
  // state, getters: 本模块内的state, getters
  // rootState, rootGetters: 根模块/根节点内的state, getters
  // rootState, rootGetters: 同时也包括各个模块中的state 和 getters
  getCounterName (state, getters, rootState, rootGetters) {
   
    // rootState.name
    // rootState.counter.counterName
    // rootState.operate.operateName
    console.log(rootState)
    // rootGetters.getName, 
    // rootGetters['counter/getCounterName']
    // rootGetters['operate/getOperateName']
    console.log(rootGetters)
    return state.counterName
  }
}
const mutations = {
   
  changeCounterName (state, payload) {
   
    state.counterName = `${
     state.counterName} ${
     payload}`
  }
}
const actions = {
   
  // context 与 store 实例具有相同方法和属性 ------  important!!!
  // context 包括: dispatch, commit, state, getters, rootState, rootGetters
  changeCounterNameAsync (context, payload) {
   
    return new Promise((resolve, reject) => {
   
      setTimeout(() => {
   context.commit('changeCounterName', payload)}, 1000)
    })
  }
}
export default {
   
  // 注意此处是namespaced,而不是names
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值