Geoff
Geoff

Reputation: 6629

Passing data properties in vue js laravel component

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 ...

Upvotes: 0

Views: 113

Answers (2)

Kumar_14
Kumar_14

Reputation: 584

In mounted:

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

Upvotes: 0

Thaadikkaaran
Thaadikkaaran

Reputation: 5226

Try using arrow function for axios callbacks

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

arrow function binds the components context as you expect.

Upvotes: 1

Related Questions