【问题标题】:Nuxt is throwing the error 'unknown action type' when I try to dispatch action from vuex store当我尝试从 vuex 商店分派动作时,Nuxt 抛出错误“未知动作类型”
【发布时间】:2021-11-26 20:10:20
【问题描述】:

我想使用操作从 Firebase 后端获取一些数据,以将其存储在 vuex 状态。目前我只是在处理一些虚拟数据。从我的 index.vue 中的商店读取数据是可行的,但是一旦我尝试在 index.vue 中获取操作,我就会收到错误,即它是未知操作类型。

商店/artikels.js

export const state = () => ({
artikel: [
    {
        id: "1",
        titel: "Hallo",
        untertitel: "Servas"
    },
    {
        id: "2",
        titel: "Was",
        untertitel: "Wos"
    },
    {
        id: "3",
        titel: "Geht",
        untertitel: "Wüst"
    }
 ]

})

export const actions = () => ({
   fetchArtikel() {
      console.log('fetch data from firebase')
   }
})

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

这是 index.vue

<script> 
import { mapActions } from 'vuex'

export default {
  name: 'App',
computed: {
  artikel() {
    return this.$store.state.artikels.artikel
  }
},
async created() {
  await this.$store.dispatch('artikels/fetchArtikel')
}
</script>

我已经尝试将 store 放在 store/index.js 中而不使用命名空间,并且还尝试通过 mapActions 和 async fetch 调度它:

import mapActions from 'vuex'

methods: {
  ...mapActions(['artikels/fetchArtikels'])
}

或:

async fetch({store}) {
  await store.dispatch('artikels/fetchArtikels')
}

到目前为止,还没有运气。有人可以帮我吗?提前致谢!

【问题讨论】:

    标签: javascript vue.js nuxt.js vuex


    【解决方案1】:

    问题是您商店的actionsgetters 是函数,但它们必须是对象:

    // store/artikels.js
    export const actions = () => ({/*...*/}) // ❌ function
    export const getters = () => ({/*...*/}) // ❌ function
    
    export const actions = {/*...*/} // ✅ object
    export const getters = {/*...*/} // ✅ object
    

    demo

    【讨论】:

      【解决方案2】:

      尝试:

      import { mapGetters, mapActions } from 'vuex'
      
      computed: {
      ...mapGetters(['artikel'}]
      },
      methods: {
        ...mapActions(['fetchArtikels'])
      },
      async created() {
        await this.fetchArtikel()
      }
      

      【讨论】:

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