zwl1619 zwl1619 - 12 days ago 6
Ajax Question

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>

Answer

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