0

Am new to Vue.js and I would like to pass the data propert value to my template.

I have:

export default {
  name: "profile",
  data: () => ({
    user:[]
  }),
  mounted() {
    axios
      .get('/api/user')
      .then(function (response) {
        this.user = response
      })
      .catch(function (response) {
        console.error(response);
      });
  }
}

In the HTML template I have:

<template>
  <div>{{user.name }}</div>
</template>

Now I am getting an error of

cannot set property user of undefined

A console.log(response) produces:

name: "user 1", // name exists
email ...

2 Answers 2

1

Try using arrow function for axios callbacks

.then((response) => {
    this.user = response
}) 

arrow function binds the components context as you expect.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this works, also i had to make a few changes ive realized that response i needed to use this.user=response.data
0

In mounted:

mounted() {
    var self = this;
    axios.get('/api/user')
        .then(function (response) {
           self.user = response
        })
        .catch(function (response) {
           console.error(response);
        });
     }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.