简体   繁体   中英

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

I have this for a page, paste of a nuxt example code from doc:

<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 shows

 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>

and no requests made to the url

The problem is that you don't close your <script> tag. This can cause these kind of weird errors (because you do have posts correctly defined in data. Adding a </script> at the end fixes this.

Also, they are using a $http plugin in their example, so the call will only work if you have that plugin. You can also just use the regular javascript fetch function to make external calls:

<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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM