vuejs3vue-sfc

Accessing element instance inside :class conditional statement in Vue3 SFC


Using a Single File Component, how can the element be accessed during a colon prefixed conditional evaluation like

:class

I tried doing:

<RouterLink to="/post-container" :class="{'is-active': (el) => subIsActive(el)}">Link Name</RouterLink>

but then the conditional doesn't work since it's not trying to execute an event handler.

My goal is check each link in a side nav menu to see which one is active according to the URL and then if it is active, change the CSS class selectors accordingly.


Solution

  • The RouterLink component adds two CSS classes to active links, router-link-active and router-link-exact-active.

    You can customize class names:

    <RouterLink :active-class="blah" :exact-active-class="blah2"/>
    

    https://router.vuejs.org/guide/essentials/active-links.html#Active-links

    If you want to access <a> my guess a sure way is to use a directive:

    <script setup>
    const vMount = {
        mounted(el, { value }) {
            value(el);
        }
    };
    </script>
    <template>
      <RouterLink v-mount="el => el.classList.toggle('active', /* some condition here */)"/>
    </template>