[Vuejs]-How to change a css style each page in vue-cli

1👍

You can consider using Vue-router with active-class prop

<ul class="nav nav-pills" id="mainNav">
  <router-link to="/" tag="li" class="dropdown" active-class="active">Home</router-link>
  <router-link to="/test1" tag="li" class="dropdown-item dropdown-toggle" active-class="active">Test1</router-link>
  <router-link to="/test2" tag="li" class="dropdown-item dropdown-toggle" active-class="active">Test2</router-link>
</ul>

Another naive solution is checking window.location.href, but it’s not simple to cover all possible cases.

<ul class="nav nav-pills" id="mainNav">
    <li class="dropdown">
        <a class="active" href="/">
            Home
        </a>
    </li>
    <li>
        <a class="dropdown-item dropdown-toggle" href="/test1" :class="getClass('/test1')">
            test1
        </a>
    </li>
    <li>
        <a class="dropdown-item dropdown-toggle" href="/test2" :class="getClass('/test2')">
            test2
        </a>
    </li>
</ul>
<script>
export default {
  methods: {
    getClass(url) {
      if (window.location.href.includes(url)) {
        return "active"
      }
      return ""
    }
  }
}
</script>
👤ittus

Leave a comment