Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue component not updated when props are async

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 witch get data with $.ajax (Promise) and set 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 the UsersService

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 get data with Promise, if I change

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

into the property, I can see the users

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

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

like image 437
Max Avatar asked May 24 '17 09:05

Max


1 Answers

You set data once "onInit" in users-list. For reactivity you can do

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

or

watch: {
    users(){
    //do something
    }
}
like image 164
Kirill Matrosov Avatar answered Sep 27 '22 22:09

Kirill Matrosov