记简书--vuex学习

785 阅读1分钟

简书链接地址: www.jianshu.com/p/a804606ad….
vuex 使用注意点 www.jianshu.com/p/3391cfb11…
官方文档 :vuex.vuejs.org/zh/guide/mo…
印象深刻:因为平时比较少用mudules,因此看到这句话,通俗易懂

Modules

由于使用单一的状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,store对象就可能变得相当的臃肿,为了解决以上的问题,vuex允许我们将store对象分割成模块。每个对象拥有自己的state、mutaction、action,getter、(甚至是嵌套子模块———从上至下进行同样形式的分割)

const moduleA={
    state:{...},//理解为data
    getter:{...},//理解为computed
    mutactions:{..}//理解为methods
    action:{...},//里面为异步提交
}
const moduleB={
    state:{...},
    getter:{...},
    mutations:{...},
    action:{...}
}
const store=new Vuex.Store({
   modules:{
       a:moduleA,
       b:moduleB
   }
})
//调用时
this.$store.state.a
this.$store.state.b

this.$store.dispatch('模块中的方法')
store 后面不需要加 a。除了 state 是分模块的,其他 mutations 和 actions 都不分模块,因此规划的时候要注意不要重名!

vuex namespaced的作用以及使用方式 !(避免重名)
 const moduleB={
   namespaced: true,
    state:{...},
    getter:{
        test(){}
    },//getters['b/test']
    mutations:{
        test(state){
            console.log('test namespaced')
        }
    },
    action:{...}
}
this.$store.commit("b/test")

getters和mutation都可以改变state的值,区别在于是否存在缓存

mapState mapGetters mapActions mapMutations

computed: {
...mapState('some/nested/module', {
  a: state => state.a,
  b: state => state.b
}),
 ...mapGetters('some/nested/module', {
  a: state => state.a,
  b: state => state.b
})
},
methods: {
...mapActions('some/nested/module', [
  'foo', // -> this.foo()
  'bar' // -> this.bar()
]),
 ...mapMutations('some/nested/module', [
  'foo', // -> this.foo()
  'bar' // -> this.bar()
])
}

如果是多个
...mapState({
      A: state => state.moduleA.A,
      B: state => state.moduleB.A,
   }
    ...mapActions([
  'some/moduleA/foo', 
  'some/moduleB/bar' 
])

方法和state不需要全部引进页面 可直接 调用 this.$store.state.moduleA.A,this.$store.dispatch('moduleA/A方法')