zoukankan      html  css  js  c++  java
  • Vuex modules的使用

    1 为什么要使用模块

    当应用变得复杂时,store对象就会变得相当臃肿,为了解决这个问题,可以将store分割成模块(module)。而每个模块拥有自己的store mutation action getter等

    2 代码

    2.1 分割模块与定义模块

    srcstoreindex.js

      modules:{
        a:moduleA,
        b:moduleB
      }
    //2 创建对象
    const moduleA = {
      state:{
        name:'张三'
      },
      getters:{
        fullname(state){
          return state.name + '先生'
        },
        fullname2(state,getters,rootState){
          return getters.fullname + rootState.counter
        }
      },
      mutations:{
        updateName(state,payload) {
          state.name = payload
        }
      },
    
      actions:{
        aUupdateName(context){
          //模块里的commit 只能commit到自己模块里的mutations,
          setTimeout(()=>{
            context.commit('updateName','王五')
          },1000)
        }
      },
      //模块里基本不会再分割
      modules:{}
    }

    2.2 使用模块 srcApp.vue

        <h2>{{$store.state.a.name}}</h2>
        <h2>{{$store.getters.fullname}}</h2>
        <h5>{{$store.getters.fullname2}}</h5>
        <button @click="updateName">修改名字</button>
        <button @click="asyncUpdateName">异步修改名字</button>
          updateName(){
            this.$store.commit('updateName','李四')
          },
          asyncUpdateName(){
            this.$store.dispatch('aUupdateName')
          }

    页面展示结果

  • 相关阅读:
    Stl源码剖析读书笔记之Alloc细节
    Lua热更系统
    Linux C++线程池
    linux sort,uniq,cut,wc.
    (转)Linux grep
    用LogParser分析IIS请求压力
    (转)MySQL主从复制的常见拓扑、原理分析以及如何提高主从复制的效率总
    AIS相关资料
    python学习笔记
    (转)MySQL InnoDB修复笔记
  • 原文地址:https://www.cnblogs.com/polax/p/13252702.html
Copyright © 2011-2022 走看看