无法在 Nuxt 2.12 中使用 $fetchState

Bal*_*áni 2 javascript fetch vue.js nuxt.js

所以我正在尝试使用文档中描述的新功能。

但是我最终得到了这个错误:

属性或方法“$fetchState”未在实例上定义,但在渲染期间被引用。

尽管我的组件清楚地定义了 fetch() 方法并且我设法从中得到了一些东西。

<template>
    <div v-if="$fetchState">
        <p v-if="$fetchState.pending">Fetching posts...</p>
        <p v-else-if="$fetchState.error">Error while fetching posts</p>
        <div v-else>
            <div v-if="content.content1" v-html="content.content1" />
            <div v-if="content.content2" v-html="content.content2" />
        </div>
    </div>
</template>
<script>
import { mapState } from 'vuex'

export default {
    async fetch({ store, error }) {
        try {
            await store.dispatch('home/fetchContent')
        } catch (e) {
            error({
                statusCode: 503,
                message: 'Unable to fetch'
            })
        }
    },
    computed: mapState({
        content: (state) => state.home.content
    })
}
</script>

Run Code Online (Sandbox Code Playgroud)

有没有人遇到过?

小智 9

当您使用 fetch(context) 时,您使用旧的 fetch,如果需要,您应该从中获取上下文。

  async fetch() {
    const { store, error } = this.$nuxt.context

    try {
      await store.dispatch('home/fetchContent')
    } catch (e) {
      error({
        statusCode: 503,
        message: 'Unable to fetch'
      })
    }
  },
Run Code Online (Sandbox Code Playgroud)

https://nuxtjs.org/blog/understanding-how-fetch-works-in-nuxt-2-12/#fetch-before-nuxt-2-12