Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue typescript ref: Cannot create property 'value' on boolean 'false'

I'm using vue with typescript and headless ui. When I try to show a dialog following this example: https://headlessui.dev/vue/dialog, I get the error: Type 'true' is not assignable to type 'Ref'

I declare the isOpen variable in my component class:

private readonly isOpen = ref<boolean>(false);

The html for the button that is opening the dialog is:

<button class="btn" @click="toggleGuestList(true)">View list</button>

The method for toggling the dialog is:

public toggleGuestList(toggle:boolean) {
   this.isOpen.value =  toggle;
}

It is when this method is activated I get the error:

Cannot create property 'value' on boolean 'false'

It seems isOpen is resolved as a plain boolean. How can I force it to see it as a ref? I tried (this.isOpen as Ref< boolean >).value = true, but it did not solve the issue.

like image 780
Simon Bob Avatar asked Jun 28 '26 11:06

Simon Bob


1 Answers

I know it's an old one, but i get the similar issue, because don't read doc carefully 🙃.

Maybe someone will find it useful, so i left answer here.

ANSWER [FROM DOC]:

Note that refs returned from setup are automatically shallow unwrapped when accessed in the template so you do not need to use .value when accessing them. They are also unwrapped in the same way when accessed on this.

setup() {
    const isOpen = ref<boolean>(false);
},
methods: {
    public toggleGuestList(toggle:boolean) {
        this.isOpen.value = toggle; // will not work (as isOpen already unwrapped)
        this.isOpen = toggle;  // will work
    }
}

If you use method inside setup then:

setup() {
    const isOpen = ref<boolean>(false);

    function toggleGuestList(toggle:boolean) {
        this.isOpen.value = toggle; // will not work as we should access to isOpen without this inside setup
        isOpen.value = toggle; // will work
    }
}
like image 196
Taras Budzyn Avatar answered Jul 01 '26 11:07

Taras Budzyn



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!