user15301306
user15301306

Reputation: 23

Vue.js 3.0: Read and set object properties from method

I am learning and creating a Vue application. When I try setting the properties, I get an error like this, Cannot read property 'Selected.type' of undefined This is how I try to do it:

<script>
 export default {
  data() {
    return {
      info: {},
      Selected: {
            type: '',
            country: '',
        }
    };
  },
  methods: {
fetchData () {
  fetch(`https://data.brreg.no/enhetsregisteret/api/enheter/983609155`)
    .then( resp => resp.json())
    .then((data) => (this.info = data))
    .then(function (data) {
     console.log(data.organisasjonsform.beskrivelse);
     this.Selected.type=data.organisasjonsform.beskrivelse;
     
     })
    .catch(err => console.error(err))
}
  },
  mounted() {
    this.fetchData();
  },
  
};
</script>

Why I am getting this error? I am new to VueJS. Can someone please help me out here?

Upvotes: 2

Views: 172

Answers (2)

Moncef Ben Slimane
Moncef Ben Slimane

Reputation: 11

This should work, I didn't try it but it's obvious. you have to add the 'this' before Selected.type to access it.

Edit: My bad, I totally forgot about the function context. That's what happens when you don't run your code before posting, i guess.

  fetch(`https://data.brreg.no/enhetsregisteret/api/enheter/983609155`)
    .then( resp => resp.json())
    .then((data) => (this.info = data))
    .then((data) => {
     console.log(data.organisasjonsform.beskrivelse);
     this.Selected.type=data.organisasjonsform.beskrivelse;
     
     })
    .catch(err => console.error(err))
}

Upvotes: 0

Nikolaj Dam Larsen
Nikolaj Dam Larsen

Reputation: 5674

This is because this refer to the execution context of the callback-function, not the Vue component. It is caused by using the function-keyword to declare your callback instead of the newer () => {} syntax.

If you change your code to:

fetch(`https://data.brreg.no/enhetsregisteret/api/enheter/983609155`)
    .then( resp => resp.json())
    .then((data) => (this.info = data))
    .then((data) => {
       console.log(data.organisasjonsform.beskrivelse);
       this.Selected.type=data.organisasjonsform.beskrivelse;
    })

It should work.

An alternative syntax, is to capture the this context in a variable within the closure of your fetchData-method

fetchData () {
  const self = this;
  fetch(`https://data.brreg.no/enhetsregisteret/api/enheter/983609155`)
    .then( resp => resp.json())
    .then((data) => (this.info = data))
    .then(function (data) {
       console.log(data.organisasjonsform.beskrivelse);
       self.Selected.type=data.organisasjonsform.beskrivelse;
     })
    .catch(err => console.error(err))
}

Upvotes: 3

Related Questions