javascript - Vue.js 错误 : TypeError: Cannot read properties of undefined

标签 javascript vue.js

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

enter image description here

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 引用 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);
          });
    }
}

关于javascript - Vue.js 错误 : TypeError: Cannot read properties of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70646023/

相关文章:

javascript - 向下滚动时,导航栏上的下拉菜单消失在后面

javascript - 如何在 Vue 中动态创建的组件上获取更新的 $refs?

javascript - 如何让按钮在某个点后改变它的步骤而不丢失值(value)?

vue.js - NuxtJS页面被创建两次

javascript - 无法在 Rails 应用程序的回调中声明变量

javascript - JQuery - 将 GUI 对象连接到事件的最佳方式?

javascript - DOM 节点清理在 d3 中如何工作?

javascript - 我如何在使用 XSLT 和 jQuery 的书中获得动态标题?

javascript - 单击时动态创建 Vue 组件

javascript - 如何在 Vue 中显示模态框?