javascript - vue 初始化數(shù)據(jù)賦值報錯
問題描述
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>報錯
TypeError: Cannot set property ’titleList’ of undefined類型錯誤,不能設(shè)置未定義的屬性,
數(shù)據(jù)response.data是一個對象數(shù)組我已經(jīng)初始化了titleList,不知為何說他未定義,求大神解答
問題解答
回答1:this 指向更改了 你可以打印出this來看一下指向誰
解決方案
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);})
這樣試下。如果不行,把錯誤貼出看下!
回答4:this指針丟失,可以使用箭頭函數(shù),也可以用一個變量保存this let _this = this
回答5:我在使用axios請求數(shù)據(jù)的時候記得是在程序入口文件main.js里面全局引入axios類庫,試試引入后用Vue.prototype.$http=axios,之后就可以在全局使用了,至于樓上給出的答案指出的this指針問題,可以試試,我習(xí)慣了es6的語法,所以項目中用的一般都是箭頭函數(shù)
回答6:axios.get(’***’).then((res) => { this.titleList=res.data;});
使用這種方式試試
相關(guān)文章:
1. mysql - 如何減少使用或者不用LEFT JOIN查詢?2. 視頻文件不能播放,怎么辦?3. mysql - jdbc的問題4. Python爬蟲如何爬取span和span中間的內(nèi)容并分別存入字典里?5. 網(wǎng)頁爬蟲 - python 爬取網(wǎng)站 并解析非json內(nèi)容6. Python如何播放還存在StringIO中的MP3?7. python - 我在使用pip install -r requirements.txt下載時,為什么部分能下載,部分不能下載8. mysql - 分庫分表、分區(qū)、讀寫分離 這些都是用在什么場景下 ,會帶來哪些效率或者其他方面的好處9. node.js - nodejs開發(fā)中常用的連接mysql的庫10. python - 編碼問題求助
