...">

Vue component doesn't update if props are asynchronous

I have this component

<template>

    <div class="list-group">
        <div v-for="user in data">
            <!-- omitted for brevity -->
        </div>
    </div>

</template>


<script>

    export default ("users-list", {
        props: ['users']
        ,

        data() {
            return {
                data: this.users
            }
        }
    });

</script>

      

This component is used from another component that receives data from $ .ajax (Promise) and sets the data

<template>
    <div>
        <users-list v-bind:users="users"></users-list>
    <div>   
</template>


<script>

    import UsersService from './users.service.js';
    import UsersList from './users.list.vue';


 export default ('users-main', {
        components: {
            'users-list': UsersList
        },
        mounted() {
            this.refresh();
        },
        data() {
            return {
                data: null,
                message: null,
                user: null
            }
        },
        methods: {
            refresh() {
                let service = new UsersService();
                service.getAll()
                    .then((data) => {
                        this.data = data;

                    })
                    .catch((error) => {
                        this.message = error;
                    })

            },
            selected(user) {
                this.user = user;
            }
        }
    });

</script>

      

And this is UserService

import $ from 'jquery';

export default class UsersService {
    getAll() {

        var url = "/Api/Users/2017";

        return new Promise((resolve, reject) => {
            $.ajax({
                url: url,
                success(data) {
                    resolve(data);
                },
                error(jq, status, error){
                    reject(error);
                }

            });
        });
    }
}

      

As you can see the service gets data using Promise

if I change

<div v-for="user in data">

      

in the property, I can see users

<div v-for="user in users">

      

Question: How can I pass async props value to components?

+3


source to share


2 answers


You set the data once "onInit" in the user list . For reactivity, you can do

computed:{
   data(){ return this.users;}
}

      



or

watch: {
    users(){
    //do something
    }
}

      

+2


source


What do you mean by:

As you can see the service is getting the data using a Promise if I change

<div v-for="user in data">



in the property, I can see users

<div v-for="user in users">

The use <div v-for="user in users">

should work, so what's the problem?

0


source







All Articles