【问题标题】:vuex unknown action (or mutation) typevuex 未知动作(或突变)类型
【发布时间】:2019-10-07 14:51:39
【问题描述】:

我正在编写一个简单的代码来在 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;
  }
}

【问题讨论】:

    标签: vuex store nuxt.js


    【解决方案1】:

    您正在使用“经典”且现已弃用的方法在 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 中看到它。

    【讨论】:

    • getter 在没有任何错误的情况下无法工作。我改为登录控制台:token: (state) => { console.log('tokenStr');返回 state.token; } 没有记录
    • getter 只有在被要求获取时才会获取。在您的一个页面或组件中尝试使用 getter,然后它应该记录。此外 ...mapGetters 是使用 getter 的好方法。这是docs 的链接,尽管该页面目前似乎处于离线状态。
    • 好吧,正如您在我的问题中看到的那样,我绝对做到了:this.token = this.$store.getters.token; (this.token 在 data 中定义)
    • 在您的问题中,您的突变中没有“状态”作为第一个参数。你改了吗?
    • tnx 供您回复;它起作用了,也许我遇到了名称不匹配的问题
    【解决方案2】:

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

        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')`
    })
    

    } }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-13
      • 2019-07-02
      • 2018-08-17
      • 2022-01-02
      • 2019-10-28
      • 2021-06-26
      • 2020-09-27
      • 1970-01-01
      相关资源
      最近更新 更多