zoukankan      html  css  js  c++  java
  • vue(30)vuex使用子模块

    如果项目很大再store的index.js里面可能就有很多的内容,不便于管理,vuex支持在主模块下面创建子模块:

    store/index.js:

    import { createStore } from 'vuex'
    //新建一个子模块,也可以将这个子模块写在外面的一个js文件中,这里引入
    const user = {
      state: {
        userName: 'jack',
        password: '123'
      },
      getters:{
        //rootState可以访问父模块的state中的内容
        fullName(state,getter,rootState){
          return state.userName + " " +rootState.name;
        }
      },
      mutations: {
        changeUserName(state,payload){
          state.userName = payload;
        }
      },
      actions:{
        //context中有state(自己模块的state),commit(自己模块的mutations),getters(自己模块的getters),
        //rootGetters(父模块的getters),rootState(父模块的state)
        smt(context,payload){
          setTimeout(()=>{
            //用父模块的name赋值给子模块的uaerName
            context.commit('changeUserName',context.rootState.name);
          },2000);
        }
      }

    }

    export default createStore({
      state: {
        name: 'tom',
        age: '10'
      },
      mutations: {
      },
      actions: {
      },
    //挂载子模块
      modules: {
        user
      }
    })
     
     
     
    访问子模块中的各个对象:
    <template>
      <div class="about">
        <h1>{{$store.state.user.userName}}</h1>
        <button @click="click1()">改变user模块中的userName值</button>
        <h1>调用模块中的getters:{{$store.getters.fullName}}</h1>
         <button @click="click2()">调用模块中的action 2s后改变值</button>
      </div>
    </template>

    <script>
    export default {
      name: 'About',
      methods: {
        click1(){
          //调用子模块的mutations中的方法时不用加上子模块的名称,vue会在所有模块中搜索,所有要保持所有模块中mutations中的方法名都不一样
          this.$store.commit('changeUserName','maycpou');
        },
        click2(){
          //调用子模块的action一样,不需要子模块的名称,所以要保持方法名不同
          this.$store.dispatch('smt','cp3');
        }
      }
    }
    </script>
  • 相关阅读:
    JavaScript 弹出层,背景变暗
    DataGridView常见用法和FAQ汇总
    将visual studio 2005 SP1补丁整合到安装文件
    非常经典的网络蜘蛛示例
    asp.net画曲线图(折线图)
    Asp.net中基类页的设计和使用
    使用 Visual C# .NET 向 Excel 工作簿传输数据
    CSS布局:让页脚始终保持底部的方法
    WinForm开发,窗体显示和窗体传值相关知识总结
    asp.net Urlrewriter在虚拟主机上的使用方法
  • 原文地址:https://www.cnblogs.com/maycpou/p/14966029.html
Copyright © 2011-2022 走看看