Vuex(4.0.2)模块化的两种写法

先放写法,下面说明

1.

//模块文件
const vxModel={ state: { //.... }, mutations: { //.... }, actions: { //.... }, getters: { //.... }, } export default vxModel

  之后引用在index引入

  

    
//store/index.js
//... import vxModel from './vxModel';//模块地址 export default createStore({ //..... modules: { vxModel }, })

  使用

//在组件中使用
<template>
//可以使用this.$store来调用,要加上导出的名字
    <div class="vxn-box">{{ this.$store.state.counter.flag }}</div>

//下面展开运算符之后就可以直接使用
    <input class="inp" type="number" name="vxn" id="vxn" v-model="numberGet" />
</template>
<script>
import { mapActions, mapGetters, mapMutations } from "vuex";

    ...mapMutations(["addReduce", "addPlus"]), //使用展开运算符映射到组件
    ...mapActions(["random"]),

    //将vuex模块中的函数封装一层get使用,change是我在mutations中写的函数
    numberGet: {
      get() {
        return this.$store.state.counter.change;
      },
      set(v) {
        return this.$store.commit("changes", v);
      },
    },
</script>

 

2.


// 模块文件
const state: { //.... }, const mutations: { //.... }, const actions: { //.... }, const getters: { //.... },
export default { namespaced: true,// 标识名字  state, mutations, actions, getters }

  index引入

//...
import vxModel from './vxModel'
export default createStore({
    //.....
  modules: {
    vxModel
  },
})

用法

<template>
 
  <div id="app">
 
    <router-view />
 
    <FooterBar v-if="isShow" />
 
  </div>
 
</template>
 
 
 
<script>
 
import{ mapState, mapGetters, mapActions } from 'vuex'
 
import FooterBar from '@/components/common/FooterBar'
 
import config from './config/index'
 
export default {
//...
 
  computed:{
 
    ...mapState({  
 
      //这里的...是超引用,ES6的语法,意思是state里有多少属性值我可以在这里放多少属性值
 
         isShow:state=>state.footerStatus.showFooter 
 
      }),
 
  },
 
  watch: {
 
    $route(to,from){
 
      if(to.name=='book'||to.name=='my'){
 
         this.$store.dispatch('footerStatus/showFooter') //这里改为'footerStatus/showFooter',
 
                                                         //意思是指footerStatus.js里actions里的showFooter方法
 
      }else{
 
         this.$store.dispatch('footerStatus/hideFooter') //同上注释
 
      }
 
    }
 
  }
 
}
 
</script>
 

推荐使用第二种,虽然麻烦一点,但在后续模块变多的情况下可以避免重名问题,而且第二种写法会让代码逻辑看起来更加清晰

3.参考

Vuex略解之Modules模块化以及mapGetters mapActions和mapState;

Module Local State

 

posted @ 2022-01-19 00:14  逐云去  阅读(393)  评论(0)    收藏  举报