当我尝试从 vuex 商店调度操作时,Nuxt 抛出错误 'unknown action type'

Nuxt is throwing the error 'unknown action type' when I try to dispatch action from vuex store

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

store/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/index.js 中而不使用命名空间,并且还尝试通过 mapActions 和异步获取来调度它:

import mapActions from 'vuex'

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

或:

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

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

试试:

import { mapGetters, mapActions } from 'vuex'

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

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

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

export const actions = {/*...*/} // ✅ object
export const getters = {/*...*/} // ✅ object

demo