Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vue.js: Update data from watcher

I have the following code:

export default {
    name: '...',
    props: ['user'],
    data() {
        return {
            userName: this.user.name
        }
    },
    watch: {
        user: (_user) => {
            this.userName = _user.name
        }
    },
    methods: {
        ...
    }
};

The userprop is updated by the parent component (it's information from the server). If I log the _user variable I have everything available. The userName prop doesn't update though.

like image 904
sandrooco Avatar asked May 27 '26 08:05

sandrooco


1 Answers

Since you are using fat arrow function as below:

user: (_user) => {
            this.userName = _user.name
        } 

The this is not pointing to the vue instance, so by using this.userName you are not refering to the userName property in your data.

So use normal function like this:

user: function(_user){
            this.userName = _user.name
        } 

There is a warning mentioned in vuejs docs regarding using an arrow function to define a watcher. You can have a look here

like image 169
Vamsi Krishna Avatar answered May 30 '26 11:05

Vamsi Krishna



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!