Home » vue » Vue3 reverse function

Vue3 reverse function

Posted by: admin November 26, 2021 Leave a comment

Questions:

I’m having some hard time with making custom dropdown for my app. I need to make a function that will add class called is-active to div.
So what I did, I have simple div and it has function on click, like so:

<div :class="is_active" @click="open">

So I have defined is_active and open in setup, like:

setup() {
    let is_active = ref('no-active');

    function open() {
      is_active.value = 'is-active';
    }
    

    return {
      is_active,
      open
    }
  }

So the idea is, when user click on that function, it will set is-active to open it and no-active to close it. I know how to do it with boolean, but how to make this work with strings?

I could do it like this:

if(is_active === 'is-active) {
  is_active.value = 'no-active'
} elseif(is_active === 'no-active' {
  is_active.value = 'is-active
}

But I think there is better way to do it.

Answers:

You can deal with boolean values, which is more natural, and bind the class dynamically.

<div :class="is_active ? 'is-active' : 'no-active'" @click="toggle">

setup() {
    let is_active = ref(false);

    const toggle = () => (is_active.value = !is_active.value)


    return {
        is_active,
        toggle
    }
 }