錯誤例子:
data() {
return {
title: '生命週期',
cera: '',
money: 1 * 5 * 6 * 4,
//listuser用於接收axios返回的數據
listuser:'',
}
methods: {
selectUser() {
this.$axios.get('/api/ListUser')
.then(function(response) {
console.log("log=", response);
this.listuser=response.data
})
.catch(function(error) {
});
}
}
當你這樣在axios中使用this.listuser的時候,會提示沒有定義listuser
原因:
在像data
和的選項函數中methods
,vue綁定this
到我們的視圖模型實例,所以我們可以使用this.contas
,但在函數裏面then
,this
沒有綁定。
解決方法1:
methods: {
var slef=this
selectUser() {
this.$axios.get('/api/ListUser')
.then(function(response) {
console.log("log=", response);
slef.listuser=response.data
})
.catch(function(error) {
});
}
}
在axios中 then裏邊是this不出來data屬性的,所以你需要在外邊定義一個this,這個時候再用你自己定義的this就可以了
解決方法2:
methods: {
selectUser() {
this.$axios.get('/api/ListUser')
.then((response)=> {
console.log("log=", response);
this.listuser=response.data
})
.catch(function(error) {
});
}
}
如果你的目標是支持現代瀏覽器(或使用像babel這樣的轉換器),您可以使用ES6標準中的箭頭功能 這樣也是可以獲取到data屬性的