vuex相关理解

刷新数据不丢失

1.vue持久化 vue-presits插件
2.放在缓存中

vuex流程

引用vuex=>注册vuex(Vue.use(vuex))=>new vuex=>导出放在vue实例上

vuex 相关属性

1.state,mutation,action,modules,getter
2.mutation触发commit action触发是dispatch

modules中nameSpace用法以及传参相关方法

nameSpace:true 调用dispatch()

const store = new Vuex.Store({
  modules: {
    account: {
      namespaced: true,
      state: {...}, // 模块内的状态已经是嵌套的,namespaced不会有影响
      getters: {      // 每一条注释为调用方法
        isAdmin () { ... } // getters['account/isAdmin']
      },
      actions: {
        login () {...} // dispatch('account/login')
     },
      mutations: {
        login () {...} // commit('account/login')
      },
      modules: {     // 继承父模块的命名空间
        myPage : {
          state: {...},
          getters: {
            profile () {...}     // getters['account/profile']
          }
        },
        posts: {    // 进一步嵌套命名空间
          namespaced: true,
          getters: {
            popular () {...}    // getters['account/posts/popular']
          }
        }
      }
    }
  }
})

如果你希望使用全局state和getter,roorState和rootGetter会作为第三和第四参数传入getter,也会通过context对象的属性传入action
若需要在全局命名空间内分发action或者提交mutation,将{ root: true }作为第三参数传给dispatch或commit即可。

modules: {
  foo: {
    namespaced: true,
    getters: {
      // 在这个被命名的模块里,getters被局部化了
      // 你可以使用getter的第四个参数来调用 'rootGetters'
      someGetter (state, getters, rootSate, rootGetters) {
        getters.someOtherGetter    // -> 局部的getter, ‘foo/someOtherGetter’
        rootGetters.someOtherGetter // -> 全局getter, 'someOtherGetter'
      }
    },
    actions: {
      // 在这个模块里,dispatch和commit也被局部化了
      // 他们可以接受root属性以访问跟dispatch和commit
      smoeActino ({dispatch, commit, getters, rootGetters }) {
        getters.someGetter    // 'foo/someGetter'
        rootGetters.someGetter    // 'someGetter'
        dispatch('someOtherAction')      // 'foo/someOtherAction'
        dispatch('someOtherAction', null, {root: true})    // => ‘someOtherAction’
        commit('someMutation')    // 'foo/someMutation'
        commit('someMutation', null, { root: true })    // someMutation
      }
    }
  }
}
mutation,action的区别

1.mutation专注于修改state,而action专注于业务代码,异步请求
2.mutation 必须同步执行,action可以异步

getter和state区别

就像计算属性一样,getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算。

vuex为什么不建议在action中修改state

当某种类型的action只有一个声明时,action的回调会被当作普通函数执行,而当如果有多个声明时,它们是被视为Promise实例,并且用Promise.all执行(Promise.all在执行Promise时是不保证顺序的)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值