【问题标题】:Switching to modules mode Vuex.Store in VueJS在 VueJS 中切换到模块模式 Vuex.Store
【发布时间】:2018-07-16 04:19:15
【问题描述】:

我正在寻找在 VueJS 中为 Vuex Store 切换到模块模式的解决方案。因为我用的是 NuxtJS,所以默认的 store 会是经典模式。

我按照以下说明操作:https://nuxtjs.org/guide/vuex-store#modules-mode 但它不起作用。

希望你的家伙能帮助我!

~/store/index.js

export const AuthenticationStore = new Vuex.Store({
    state: {
      authUser: null,
      userInfo: null,
      token: null
    },
    mutations: {
      SET_USER: function (state, user) {
        state.authUser = user
      },
      SET_TOKEN: function (state, token) {
        state.token = token
        instance.defaults.headers = { Authorization: 'Bearer ' + token }
      }
    },
    actions: {
      async nuxtServerInit ({ commit }, { req }) {
        try {
          const jwtCookie = req.headers.cookie.split(';').find(c => c.trim().startsWith('token='))
          if (jwtCookie) {
            let token = jwtCookie.split('=')[1]
            let payload = jwtDecode(token)
            let date = Date.now() / 1000
            if (payload.exp > date) {
              commit('SET_USER', payload)
              commit('SET_TOKEN', token)
              instance.defaults.baseURL = backendURL
            }
          }
        } catch (error) {
          console.log('nuxtServerInit Failed')
        }
      },
      async login ({ commit }, { username, password }) {
        try {
          const { data } = await axios.post('http://localhost:8000/api/v1/api-token-auth/login', {
            username,
            password
          })
          let payload = jwtDecode(data.token)
          Cookie.set('token', data.token, {
            expires: null
          })
          commit('SET_TOKEN', data.token)
          commit('SET_USER', payload)
        } catch (error) {}
      },
      async logout ({ commit }) {
        Cookie.remove('token')
        commit('SET_USER', null)
        commit('SET_TOKEN', null)
        window.location.href = '/'
      }
    },
    modules: {
      ...
    }
  })

错误:

[vuex] unknown action type: login 在组件中调度操作时:

async login () {
      try {
        await this.$store.dispatch('login', {
          username: this.signupUsername,
          password: this.signupPassword
        })
        this.signupUsername = ''
        this.signupPassword = ''
      } catch (e) {}
    }

我想切换到带有 write export const store 的模块,以便将 const store 导入到我项目中的其他 js 文件中。

【问题讨论】:

  • 你试过什么?为什么它不起作用?你得到什么样的错误?
  • 已修复。反正。谢谢!

标签: vue.js vuejs2 vuex


【解决方案1】:

由于您使用的是模块化方法,因此您需要添加 { root : true} 来访问根操作、突变、getter 等。例如:

$store.dispatch('login', { 用户名:this.signupUsername,密码: this.signupPassword }, { root : true} )

`

【讨论】:

  • 同样得到错误node_modules\vuex\dist\vuex.esm.js:417 [vuex] unknown action type: login
  • 已修复。反正。谢谢!
  • 不,我的 Vuex 有一些问题,我还是修好了 :)
猜你喜欢
  • 2015-08-03
  • 2017-11-24
  • 2011-02-06
  • 2017-01-08
  • 1970-01-01
  • 2013-02-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多