vuex 未知动作(或突变)类型

vuex unknown action (or mutation) type

我正在编写一个简单的代码来在 Nuxt 应用程序中设置存储中的令牌。当我尝试从我的商店调用突变或操作时,此错误记录在控制台中:[vuex] unknown action type: setToken

import Vuex from 'vuex';

export const store = new Vuex.Store({
    state:()=> ({
        token: ''
    }),
    getters: {
        getToken: state => {
            return state.token;
        }
    },
    mutations: {
        setToken: (tokenStr) => {
            state.token = tokenStr;
        }
    },
    actions: {
        setToken: ({ commit }, tokenStr) => {
            commit('setToken', tokenStr);
        }
    }
})

这是一个尝试调用突变的方法:

methods:{
  setToken(){
    this.$store.dispatch('setToken','token1');
    this.token = this.$store.getters.token;
  }
}

您正在使用 'classic' 在 nuxt 中设置 vuex 存储的方法,现在已弃用。您应该这样设置:

// store/index.js
export const state = () => ({
  token: ''
})

export const mutations = {
  SET_TOKEN (state, tokenStr) {
    state.token = tokenStr
}

export const actions = {
  setToken ({ commit }, tokenStr) {
    commit('SET_TOKEN', tokenStr)
  }
}

export const getters = {
  token: (state) => state.token
}

Nuxt 将从那里为您建立商店。你可以在文档中看到它 here.

您可以使用 this.$store.dispatch('xxx') 在组件中调度操作,或使用映射组件方法到 store.dispatch 调用的 mapActions 助手(需要根存储注入) : 尝试另一种调度操作的方法

    import { mapActions } from 'vuex'

export default {
  // ...
  methods: {
...mapActions([
  'increment', 
// map `this.increment()` to 

this.$store.dispatch('increment')

  // `mapActions` also supports payloads:
  'incrementBy' // map `this.incrementBy(amount)` to `this.$store.dispatch('incrementBy', amount)`
]),
...mapActions({
  add: 'increment' // map `this.add()` to `this.$store.dispatch('increment')`
})

} }