zwl1619
zwl1619

Reputation: 4232

vue.js 2.0 : Data gotten from backend via ajax can not be shown in view

I am using vue.js 2.0,This demo below is working.

<div class="container" id="app">
    <ol>
        <li v-for="(todo,index) in todos">
            {{ index }} {{ todo.text }}
        </li>
    </ol>

</div>

<script>
    new Vue({
        el: '#app',
        data: {
            todos: [
                { text: 'Learn JavaScript' },
                { text: 'Learn Vue' },
                { text: 'Build something awesome' }
            ]
        }
    });
</script>

I use axios(https://github.com/mzabriskie/axios) to send ajax requests and get the data from backend,I can see the data in console,but the data can not be shown in view. enter image description here

<div class="container" id="app">
    <ol>
        <li v-for="(todo,index) in todos">
            {{ index }} {{ todo.text }}
        </li>
    </ol>

</div>

<script>
    new Vue({
        el: '#app',
        data: {
            todos: []
        },
        mounted: function () {
            this.$nextTick(function () {
                axios.get('/articles')
                    .then(function (response) {
                        console.log(response);
                        this.todos = response.data;
                    })
                    .catch(function (error) {
                        console.log(error);
                    });
            });
        }
    });
</script>

And, the simulation below is working.

<div class="container" id="app">
        <ol>
            <li v-for="(todo,index) in todos">
                {{ index }} {{ todo.text }}
            </li>
        </ol>

    </div>

    <script>
        new Vue({
            el: '#app',
            data: {
                todos: []
            },
            mounted: function () {
                this.$nextTick(function () {
                    var arr=[
                        { text: 'Learn JavaScript' },
                        { text: 'Learn Vue' },
                        { text: 'Build something awesome' }
                    ];
                    this.todos = arr;
                });
            }
        });
    </script>

Upvotes: 0

Views: 175

Answers (1)

Gena
Gena

Reputation: 36

I think, you need preserve "this" before axios.get (self=this) and then change this.todos = response.data; to self.todos = response.data;

Upvotes: 2

Related Questions