【问题标题】:Vue.js error: TypeError: Cannot read properties of undefinedVue.js 错误:TypeError:无法读取未定义的属性
【发布时间】:2022-01-09 22:23:28
【问题描述】:

我对 vue.js 的了解有限,但据我所知,这应该可行,由于某种原因,当我尝试访问数据属性中的变量时,它找不到它。

data: function() {
    return {
        id: 0,
        clients: []
    }
},
methods: {
    getClientData(){
        fetch('/view-clients/' + this.id).then(function (response) {
            return response.text();
        }).then(function (data) {
            this.clients = JSON.parse(data);
            this.id = this.clients[clients.length - 1].id;
        }).catch(function (error) {
            console.log('Error: ' + error);
        });
    }
}

【问题讨论】:

  • 错字?应该是this.clients[this.clients.length - 1].id
  • 另外,函数范围适用于这里,因为你没有使用箭头函数,所以this 不是你想象的那样。
  • 即使应用了上述 cmets,是否预期“工作”并不取决于返回的解析结果。然而,关于这究竟是什么,没有提供足够的信息。也就是说,这个问题并不代表一个完整的最小复制。
  • 使用箭头函数,否则你的回调中的this 不会引用 Vue 组件实例。另外,clients 是未定义的:你的意思是 this.clients[this.clients.length - 1].id 吗?

标签: javascript vue.js


【解决方案1】:

函数范围很可能是罪魁祸首。请改用箭头函数,以便 this 引用 Vue 组件。

data() {
    return {
        id: 0,
        clients: []
    }
},
methods: {
    getClientData(){
        fetch('/view-clients/' + this.id).then((response) => response.text())
          .then((data) => {
            this.clients = JSON.parse(data);
            this.id = this.clients[this.clients.length - 1].id;
          }).catch((error) => {
            console.log('Error: ' + error);
          });
    }
}

【讨论】:

    猜你喜欢
    • 2019-11-24
    • 1970-01-01
    • 2021-08-30
    • 2020-12-18
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 2020-01-19
    相关资源
    最近更新 更多