vue - vuex模块化

定义moon.js:

必须要在每个模块中添加namespace: true属性,不然会报错

也可以把dog模块域cat模块单独的定义在一个文件中,export defautl暴露然后moon.js引入

复制代码
import Vue from 'vue'
//引入vuex
import Vuex from 'vuex'
//使用vuex插件
Vue.use(Vuex)

//模块化
//关于dog的模块
const dog={
  //异步操作
  actions: {

  },
  //state成员操作
  mutations: {

  },
  //加工state成员给外界
  getters: {

  },
  //state 存放状态
  state: {

  }
}


//关于cat的模块
const cat={
  //异步操作
  actions: {

  },
  //state成员操作
  mutations: {

  },
  //加工state成员给外界
  getters: {

  },
  //state 存放状态
  state: {

  }
}

export default new Vuex.Store({
//使用模块化 modules: {
//myDog: dog, //myCat: cat dog, cat } })
复制代码

 

模块化之后如何调用方法与数据:

map调用

复制代码
<script>
//引入mapActions
  import {mapActions,mapMutations,mapGetters,mapState} from 'vuex'
  export default {
    //mapGetters与mapState映射
    computed: {
      //sate数组写法
      ...mapState('dog',['name','age']),
      ...mapState('cat',['name','age']),
      //getters数组写法
      ...mapGetters('dog',['lastName']),
      ...mapGetters('cat',['lastName']),

      //sate对象写法
      ...mapState('dog',{name: 'name',age: 'age'}),
      ...mapState('cat',{name: 'name',age: 'age'}),
      //getters对象写法
      ...mapGetters('dog',{lastName: 'lastName'}),
      ...mapGetters('cat',{lastName: 'lastName'})
    },
    //mapActions与mapMutations映射
    methods: {
      //mapActions对象写法
      ...mapActions('dog',{setName: 'setName'}),
      ...mapActions('cat',{setName: 'setName'}),
      //mapMutations对象写法
      ...mapMutations('dog',{setName: 'SETNAME'}),
      ...mapMutations('cat',{setName: 'SETNAME'}),
      
      //mapActions数组写法
      ...mapActions('dog',['setName']),
      ...mapActions('cat',['setName']),
      //mapMutations数组写法
      ...mapActions('dog',['SETNAME']),
      ...mapActions('cat',['SETNAME']),
    }
  }
</script>
复制代码

不使用map,原生调用:

 必须要在每个模块中添加namespace: true属性,不然会报错

复制代码
<script>
  export default {
    methods: {
      mess(){
        //Actions
        this.$store.commit(['dog/setName'],'levi')
        this.$store.commit(['cat/setName'],'levi')
        //Mutations
        this.$store.commit(['dog/SETNAME'],'levi')
        this.$store.commit(['cat/SETNAME'],'levi')
        //Getters
        this.$store.getters(['dog/lastName'])
        this.$store.getters(['cat/lastName'])
        //State
        this.$store.state.dog.name
        this.$store.state.cat.name
      }
    }
  }
</script>
复制代码

 

posted on   每天积极向上  阅读(114)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· AI与.NET技术实操系列(六):基于图像分类模型对图像进行分类
点击右上角即可分享
微信分享提示