Home > front end >  Vue.js error: TypeError: Cannot read properties of undefined
Vue.js error: TypeError: Cannot read properties of undefined

Time:01-10

My knowledge of vue.js is limited but as far as i'm aware this should work, for some reason when I try to access my variable in the data property it can't find it.

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

CodePudding user response:

Function scope is most likely the culprit. Use arrow functions instead so this refers to the Vue component.

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);
          });
    }
}
  •  Tags:  
  • Related