<!DOCTYPE html>
<html>
<head>
<title>Welcome to Vue</title>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
<button v-on:click="sendTime">Load</button>
<div v-for="user in users">
<p>{{ user.username }}</p>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
new Vue({
el: '#app',
data: {
users: [
{ username: "billy" },
{ username: "ryan" }
],
},
methods: {
sendTime : function () {
axios.get('/api/users')
.then(function (response) {
console.log(response.data);
this.users = response.data;
})
.catch(function (error) {
console.log(error);
});
},
}
})
</script>
</body>
</html>
console.log返回 -
Array [Object,Object,Object,Object,Object,Object,Object,Object,Object,Object,15 more ...]
出于某种原因,我似乎无法将此数组分配给'this.data'?单击按钮时,唯一的更改是新的console.log,但会显示数据中的两个默认用户。任何帮助将不胜感激!
答案 0 :(得分:1)
axios.get(...).then(function(response){
this.users = response.data;
}.bind(this))
答案 1 :(得分:1)
您可以维护对Vue对象的引用,然后在回调中使用该引用。
methods: {
sendTime : function () {
var self = this;
axios.get('/api/users')
.then(function (response) {
console.log(response.data);
self.users = response.data;
})
.catch(function (error) {
console.log(error);
});
},
}