首页 >社区问答列表 >javascript - vue 初始化数据赋值报错

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,不知为何说他未定义,求大神解答

  • 伊谢尔伦
  • 伊谢尔伦    2017-06-26 10:57:476楼

    this 指向更改了 你可以打印出this来看一下指向谁


    解决方案

    1.用箭头函数吧
    2.保存this (let _this = this)

    +0添加回复

  • 回复
  • 过去多啦不再A梦
  • 过去多啦不再A梦    2017-06-26 10:57:474楼

    this.axios.get('XX')
        .then(function (response) {
          response=response.body;
          this.titleList=response.data;
        })
        .catch(function (error) {
          console.log(error);
    })
    

    这样试下。如果不行,把错误贴出看下!

    +0添加回复

  • 回复
  • 習慣沉默
  • 習慣沉默    2017-06-26 10:57:472楼

    我在使用axios请求数据的时候记得是在程序入口文件main.js里面全局引入axios类库,试试引入后用Vue.prototype.$http=axios,之后就可以在全局使用了,至于楼上给出的答案指出的this指针问题,可以试试,我习惯了es6的语法,所以项目中用的一般都是箭头函数

    +0添加回复

  • 回复