1

I have Users.vue component in my NuxtJS project. It's look like:

<template>
<section>
  <h1>{{ pageTitle }}</h1>
  <ul>
    <li v-for="user of users" :key="user">
        <a href="#" @click.prevent="goTo(user)">User {{ user }}</a>
    </li>
  </ul>
</section>
</template>

<script>
    export default {
        asyncData() {
            return new Promise(resolve => {
                setTimeout(() => {
                    resolve({
                        users : [1,2,3,4,5]
                    })
                }, 3000)
            })
        },
        data() {
            return {
                pageTitle: "Это страница с пользователями"
            }
        },
        methods: {
            goTo(user) {
                return this.$router.push('/users/' + user)
            }
        }
    }
</script>


When I use promise in asyncData(), I have error [Vue warn]: Property or method "users" 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.

4
  • 2
    the asyncData() is only available in page components. Get the users data inasyncData() of page component first, and pass it to the components inside of page component Commented Jul 14, 2021 at 7:01
  • Doc Commented Jul 14, 2021 at 7:43
  • thanks for the answer. but how can I pass data from page to component? Commented Jul 14, 2021 at 8:01
  • Via props. Or use the fetch() hook. Commented Jul 14, 2021 at 11:17

1 Answer 1

1

You can use fetch hook, but on client fetch executed after page is opened. https://nuxtjs.org/docs/2.x/features/data-fetching#the-fetch-hook

For "Property or method 'users' is not defined" add "default" users to data or use <li v-if="users" v-for="user of users" :key="user">

<template>
<section>
  <h1>{{ pageTitle }}</h1>
  <ul>
    <li v-for="user of users" :key="user">
        <a href="#" @click.prevent="goTo(user)">User {{ user }}</a>
    </li>
  </ul>
</section>
</template>

<script>
    export default {
        fetch() {
          return new Promise(resolve => {
                setTimeout(() => {
                      this.users = [1,2,3,4,5];                        
                      resolve();
                }, 3000)
            })
        },
        data() {
            return {
                users: [],
                pageTitle: "Это страница с пользователями"
            }
        },
        methods: {
            goTo(user) {
                return this.$router.push('/users/' + user)
            }
        }
    }
</script>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.