【问题标题】:Unable to find Vuex module action in Nuxt在 Nuxt 中找不到 Vuex 模块操作
【发布时间】:2019-05-30 04:28:10
【问题描述】:

我正在开发一个带有自定义 Django 后端的 Nuxt 站点,我正在尝试设置一种机制,在该机制中,当应用程序加载时,我调用 /token/ URL 来获取 CSRF 令牌,然后存储它处于 Vuex 状态,用于为每个后续请求设置的自定义标头。

首先,这是我的store/index.js

import Vue from 'vue'
import Vuex from 'vuex'
import auth from '@/store/auth'

const debug = process.env.NODE_ENV !== 'production'

Vue.use(Vuex)

const store = () => {
  return new Vuex.Store({
    namespaced: true,
    modules: {
      auth
    }
  })
}
export default store

store/auth.js:

import { SET_TOKEN } from './types'

const state = () => ({
  token: ''
})

const getters = {
  token: state => state.token
}

const actions = {
  setToken({ commit, dispatch }, token) {
    commit(SET_TOKEN)
  }
}

const mutations = {
  [SET_TOKEN](state, token) {
    state.token = token
  }
}

export default {
  state,
  getters,
  mutations,
  actions
}

我想不通的一件事是将我的挂载函数放在哪里,所以它总是在页面重新加载时触发。在常规的 Vue 应用程序中,它是 App.vue,但我无法在 Nuxt 中找到相同的东西。现在,我只使用index.vue。我也在使用@axios Nuxt 模块与后端进行通信。

<script>
import Cookie from 'js-cookie'

export default {
  mounted() {
    this.getCSRFToken()
  },
  methods: {
    async getCSRFToken() {
      // Call the URL that sets the csrftoken cookie
      const tokenRequest = await this.$axios.$get('/token/')
      // Get the cookie value
      const token = Cookie.get('csrftoken')
      // Save it to the store./
      this.$store.dispatch('auth/setToken', token)
    }
  }
}
</script>

我可以很好地调用 URL 并从 cookie 中获取值,但是当我去调度我的操作时,我收到一个错误,上面写着 [vuex] unknown action type: auth/setToken

我按照示例here 设置我的状态。我的问题是:

  1. 在 Nuxt 中,我可以使用什么来始终在页面刷新/初始加载时加载它?

  2. 我需要在设置中进行哪些更改才能找到我的操作?

【问题讨论】:

    标签: authentication vuejs2 axios csrf nuxt.js


    【解决方案1】:

    问题是您的 auth 模块没有命名空间。

    将默认导出更改为

    export default {
      namespaced: true,
      state,
      getters,
      mutations,
      actions
    }
    

    您可能应该从根存储中删除 namespaced: true


    我建议您更改为使用 Nuxt 的 Module Mode,因为您使用的 Classic Mode 将在 Nuxt 3 中删除。例如

    // store/auth.js
    import { SET_TOKEN } from './types'
    
    export const state = () => ({
      token: ''
    })
    
    export const actions = {
      setToken({ commit, dispatch }, token) {
        commit(SET_TOKEN)
      }
    }
    
    export const mutations = {
      [SET_TOKEN](state, token) {
        state.token = token
      }
    }
    

    【讨论】:

    • 那么,如果我使用模块模式,我不必在任何地方设置namespaced: true,对吗?
    猜你喜欢
    • 2020-01-29
    • 2020-01-01
    • 2020-04-29
    • 2022-01-07
    • 2021-08-02
    • 2021-01-06
    • 2022-06-10
    • 2018-04-25
    • 2021-12-29
    相关资源
    最近更新 更多