javascript - vue 初始化數據賦值報錯
問題描述
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類型錯誤,不能設置未定義的屬性,
數據response.data是一個對象數組我已經初始化了titleList,不知為何說他未定義,求大神解答
問題解答
回答1:this 指向更改了 你可以打印出this來看一下指向誰
解決方案
1.用箭頭函數吧 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指針丟失,可以使用箭頭函數,也可以用一個變量保存this let _this = this
回答5:我在使用axios請求數據的時候記得是在程序入口文件main.js里面全局引入axios類庫,試試引入后用Vue.prototype.$http=axios,之后就可以在全局使用了,至于樓上給出的答案指出的this指針問題,可以試試,我習慣了es6的語法,所以項目中用的一般都是箭頭函數
回答6:axios.get(’***’).then((res) => { this.titleList=res.data;});
使用這種方式試試
相關文章:
1. MYSQL 根據兩個字段值查詢 但兩個值的位置可能是互換的,這個怎么查?2. 求救一下,用新版的phpstudy,數據庫過段時間會消失是什么情況?3. mysql replace 死鎖4. mysql - C#連接數據庫時一直這一句出問題int i = cmd.ExecuteNonQuery();5. javascript - 微信網頁開發從菜單進入頁面后,按返回鍵沒有關閉瀏覽器而是刷新當前頁面,求解決?6. extra沒有加載出來7. android - 安卓做前端,PHP做后臺服務器 有什么需要注意的?8. python - 數據與循環次數對應不上9. php傳對應的id值為什么傳不了啊有木有大神會的看我下方截圖10. mysql - ubuntu開啟3306端口失敗,有什么辦法可以解決?
