【问题标题】:How to subscribe mutation changes of a store with multiple modules?如何订阅具有多个模块的商店的突变更改?
【发布时间】:2019-07-29 09:24:10
【问题描述】:

使用vue.js 构建登录页面。在我的项目中,我将我的商店分为两个模块(用户、信息)。

在User模块中,actions.js旨在处理一些异步请求(如登录、注册),并提交相应的变异。

export const userActions = {
  login({commit}, loginUser) {
    commit(LOGIN)
    axios.post(`${ API_BASE_USER }/login`, loginUser)
         .then(res => {
           const { token } = res.data
           if (res.status == 200) { commit(LOGIN_SUCCESS, token) }
           else { commit(LOGIN_FAILURE, res.data) }
         })
  }
.......
}

我知道:In Vuex, we can subscribe store mutations. 我想订阅Login.vue 中的每个突变变化 所以我可以加载一个通知来告诉用户登录是否成功。

Login.vue

created () {
    this.$store.subscribe(mutation => {
      switch (mutation.type) {
        case LOGIN_SUCCESS:
          console.log('view success')
        // load success nitification
          break

        case LOGIN_FAILURE:
          console.log('view failure')
       // load success nitification
          break

        case LOGIN_WARNING:
          console.log('view warning')
          break
      }
    })
}

但这似乎行不通。 是否不可能在具有多个模块的商店中订阅特定模块的突变?

【问题讨论】:

  • `这似乎不起作用`是什么意思?
  • 例如:一个用户登录成功,所以actions.jscommit(LOGIN_SUCCESS),我订阅了Login.vue中的mutation变化,在switch这句话中可以看到,当@987654333 @ 打印“查看成功”。但它什么也没打印......
  • 你使用namespace作为存储模块吗?
  • 是的,我写了namespaced: true

标签: vue.js vuex


【解决方案1】:

由于您使用存储模块的命名空间,因此您在订阅时需要考虑它。例如:

created () {
    this.$store.subscribe(mutation => {
      switch (mutation.type) {
        case MODULE_NAME + '/' + LOGIN_SUCCESS:
          console.log('view success')
        // load success nitification
          break
        ...
      }
    })
}

【讨论】:

    猜你喜欢
    • 2018-04-02
    • 2019-06-12
    • 2019-06-01
    • 2019-03-06
    • 1970-01-01
    • 2018-02-16
    • 1970-01-01
    • 1970-01-01
    • 2020-07-29
    相关资源
    最近更新 更多