javascript - vue 初始化數(shù)據(jù)賦值報(bào)錯(cuò)
問(wèn)題描述
vue代碼<script>import axios from ’axios’;export default { data() {return { titleList: [],} }, created() {this.axios.get(’XX’).then(function(response) { console.log(response.data); this.titleList=response.data;}).catch(function (error) { console.log(error);}); }}</script>報(bào)錯(cuò)
TypeError: Cannot set property ’titleList’ of undefined類(lèi)型錯(cuò)誤,不能設(shè)置未定義的屬性,
數(shù)據(jù)response.data是一個(gè)對(duì)象數(shù)組我已經(jīng)初始化了titleList,不知為何說(shuō)他未定義,求大神解答
問(wèn)題解答
回答1:this 指向更改了 你可以打印出this來(lái)看一下指向誰(shuí)
解決方案
1.用箭頭函數(shù)吧 2.保存this (let _this = this)
回答2:.then(res => { this.titleList = res;})回答3:
this.axios.get(’XX’) .then(function (response) { response=response.body; this.titleList=response.data; }) .catch(function (error) { console.log(error);})
這樣試下。如果不行,把錯(cuò)誤貼出看下!
回答4:this指針丟失,可以使用箭頭函數(shù),也可以用一個(gè)變量保存this let _this = this
回答5:我在使用axios請(qǐng)求數(shù)據(jù)的時(shí)候記得是在程序入口文件main.js里面全局引入axios類(lèi)庫(kù),試試引入后用Vue.prototype.$http=axios,之后就可以在全局使用了,至于樓上給出的答案指出的this指針問(wèn)題,可以試試,我習(xí)慣了es6的語(yǔ)法,所以項(xiàng)目中用的一般都是箭頭函數(shù)
回答6:axios.get(’***’).then((res) => { this.titleList=res.data;});
使用這種方式試試
相關(guān)文章:
1. docker - 各位電腦上有多少個(gè)容器啊?容器一多,自己都搞混了,咋辦呢?2. java - spring boot 如何打包成asp.net core 那種獨(dú)立應(yīng)用?3. java - 在用戶(hù)不登錄的情況下,用戶(hù)如何添加保存到購(gòu)物車(chē)?4. datetime - Python如何獲取當(dāng)前時(shí)間5. docker start -a dockername 老是卡住,什么情況?6. javascript - nginx反向代理靜態(tài)資源403錯(cuò)誤?7. docker網(wǎng)絡(luò)端口映射,沒(méi)有方便點(diǎn)的操作方法么?8. 安全性測(cè)試 - nodejs中如何防m(xù)ySQL注入9. javascript - 關(guān)于apply()與call()的問(wèn)題10. python - 調(diào)用api輸出頁(yè)面,會(huì)有標(biāo)簽出現(xiàn),請(qǐng)問(wèn)如何清掉?
