Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vuejs boolean props watch doesn't trigger

I'm working on a vue cli project where items have two state equipped and unequipped.

This State is controlled by a Boolean located in the Props. Since you can switch the state I had to create a data isEquipped set to false by default.

I then added a watcher but it doesn't change my data value if my props is set to True.

Here's the code

name: "Item",
        props: {
            Index : Number,
            name: String,
            desc : String,
            bonus: Array,
            equipped  : Boolean
        },
        data() {
            return {
                isEquipped : false
            }
        },
        watch: {
            equipped: function(stateEquipped) {
                this.isEquipped = stateEquipped;
            },
        },

So for instance let's say I created a new item with equipped set to True, the watcher doesn't trigger and isEquipped stays at False, is there any reason to that ?

I came across multiple similar questions like this one Vue @Watch not triggering on a boolean change but none of them helped me

like image 939
Mathieu Barco Avatar asked Nov 01 '25 08:11

Mathieu Barco


1 Answers

If you want to use watch then you can try define it as:

equipped: {
    handler () {
        this.isEquipped = !this.isEquipped;
    },
    immediate: true
}

This will change the value of this.isEquipped whenever the value of equipped will change.

like image 96
Yash Maheshwari Avatar answered Nov 03 '25 23:11

Yash Maheshwari



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!