簡體   English   中英

Nuxt 屬性或方法未在實例上定義,但在渲染期間被引用

[英]Nuxt property or method is not defined on the instance but referenced during render

我有這個頁面,粘貼來自doc的nuxt示例代碼:

<template>
<div>
   {{ posts }}
</div>
</template>

<script>
export default {
  data: () => ({
    posts: []
  }),
  async fetch() {
    this.posts = await this.$http.$get('https://api.nuxtjs.dev/posts')
  }
}

npm run dev顯示

 ERROR  [Vue warn]: Property or method "posts" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://v2.vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.

found in

---> <Pages/test.vue> at pages/test.vue
       <Nuxt>
         <.nuxt/layouts/default.vue> at .nuxt/layouts/default.vue
           <Root>

並且沒有向 url 提出請求

問題是您沒有關閉<script>標記。 這可能會導致這些奇怪的錯誤(因為您確實在數據中正確定義了帖子。在末尾添加</script>可以解決此問題。

此外,他們在他們的示例中使用了 $http 插件,因此只有在您擁有該插件時調用才會起作用。 您也可以只使用常規的 javascript fetch function 進行外部調用:

<template>
  <div>
    {{ posts }}
  </div>
</template>

<script>
export default {
  data: () => ({
    posts: [],
  }),
  async fetch() {
    const response = await fetch('https://api.nuxtjs.dev/posts');
    this.posts = await response.json();
  },
};
</script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM