javascript - vue 初始化數(shù)據(jù)賦值報(bào)錯(cuò)
問題描述
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類型錯(cuò)誤,不能設(shè)置未定義的屬性,
數(shù)據(jù)response.data是一個(gè)對(duì)象數(shù)組我已經(jīng)初始化了titleList,不知為何說他未定義,求大神解答
問題解答
回答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類庫(kù),試試引入后用Vue.prototype.$http=axios,之后就可以在全局使用了,至于樓上給出的答案指出的this指針問題,可以試試,我習(xí)慣了es6的語(yǔ)法,所以項(xiàng)目中用的一般都是箭頭函數(shù)
回答6:axios.get(’***’).then((res) => { this.titleList=res.data;});
使用這種方式試試
相關(guān)文章:
1. mysql優(yōu)化 - mysql 一張表如果不能確保字段列長(zhǎng)度一致,是不是就不需要用到char。2. mysql 怎么做到update只更新一行數(shù)據(jù)?3. 使用python中的pandas求每個(gè)值占該列的比例4. javascript - 新浪微博網(wǎng)頁(yè)版的字?jǐn)?shù)限制是怎么做的5. python - scrapy 如何組合2個(gè)不同頁(yè)面的數(shù)據(jù),一并存儲(chǔ)6. python2.7 - python 函數(shù)或者類 代碼的執(zhí)行順序7. sublime可以用其他編譯器替換嗎?8. javascript - 用jsonp抓取qq音樂總是說回調(diào)函數(shù)沒有定義9. python - 多態(tài)調(diào)用方法時(shí)卻顯示bound method...10. node.js - mysql如何通過knex查詢今天和七天內(nèi)的匯總數(shù)據(jù)
