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>
  • 相关阅读:
    CSS 文档流布局以及盒子模型
    CSS样式继承和样式权重
    CSS选择器餐厅练习
    node.js读写json文件
    C#单例模式的2种实现方式,Lazy模式和双检锁模式
    The Entity Framework provider type 'MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.EntityFramework, Version=8.0.18.0,
    mysql主从配置
    nginx 限制ip并发数,nginx限制IP连接数的范例参考
    certbot 调用cloudflare api申请证书
    proxy_pass url 反向代理的坑
  • 原文地址:https://www.cnblogs.com/maycpou/p/14966029.html
Copyright © 2011-2022 走看看