Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Computed property was assigned to but it has no setter - a toggle component

I am creating a simple switch toggle component in Vue where it has a v-model and @updated. But I can't seem to change the model when the user toggles the switch. First I was getting the error to avoid mutating a prop directly. But now I am getting another error.

[Vue warn]: Computed property "isSwitchOn" was assigned to but it has no setter.

The component is meant to be used like this

<iswitch v-model="switchGender" @updated="handleUpdatedGender" />

Here is the component itself

export default {
    template: `
        <span
            @click="toggleSwitch"
            :class="{ active: isSwitchOn }">

            <span class="toggle-knob"></span>
        </span>
    `,

    props: ['value'],

    methods:
    {
        toggleSwitch()
        {
            this.isSwitchOn = !this.isSwitchOn

            this.$emit('input', this.isSwitchOn)
            this.$emit('updated')
        }
    },

    computed:
    {
        isSwitchOn()
        {
            return this.value
        }
    },
};
like image 430
Liga Avatar asked Mar 11 '19 07:03

Liga


1 Answers

The error is triggered by this statement: this.isSwitchOn = !this.isSwitchOn. You are trying to assign a value to a computed property but you didn't provide a setter.

You need to define your computed property as follow for it to work as a getter and a setter:

computed:
{
    isSwitchOn:
    {
        get()
        {
            return this.value
        },
        set(value)
        {
            this.value = value
        }
    }
}

Also, it is not advised to mutate a prop directly. What you could do is to add a new data property and sync it with the value prop using a watcher.

I think something like this will work:

props: ['value'],
data()
{
    return {
       val: null
    }
},
computed:
{
    isSwitchOn:
    {
        get()
        {
            return this.val
        },
        set(value)
        {
            this.val = value
        }
    }
},
watch: {
   value(newVal) {
       this.val = newVal
   }
}
like image 64
Kamga Simo Junior Avatar answered Nov 17 '22 06:11

Kamga Simo Junior