BigJobbies
BigJobbies

Reputation: 4055

Checking for multiple route paths in vue v-bind

I am currently adding a class to a li element based on the route.path using the following code;

<li v-bind:class="{ 'current': $route.path == '/services' }"><nuxt-link to="/services">Services</nuxt-link>

I want to check for multiple paths but i am unsure if that is possible.

Any help would be great.

Upvotes: 1

Views: 126

Answers (1)

tony19
tony19

Reputation: 138696

It's possible to check for mulitple paths by using an array of possible values, and then Array.prototype.includes to check for existence:

<li v-bind:class="{ 'current': ['/services', '/contact', '/about'].includes($route.path) }">

To improve template readability, consider moving that to a computed prop:

<template>
  <li v-bind:class="myClasses">
  ...
</template>

<script>
export default {
  computed: {
    myClasses() {
      return {
        const possiblePaths = ['/services', '/contact', '/about']
        current: possiblePaths.includes(this.$route.path)
      }
    }
  }
}
</script>

Upvotes: 2

Related Questions