[Vuejs]-How can I switch the `selected` style easily in Vue?

0👍

Take a look at Cass and Style Binding Docs

pseudo example below, also added some shorcuts to vue-router to avoid the router-link component, you just can bind the :to to the <li>

<li
   v-for="(item, $index) in routes" 
   @click="selectedIndex = $index"
   :class="{'item-selected': $index == selectedIndex}"
   :to="item.path">{{ item.name }}</li>


// on component
data() {
  return { 
    selectedIndex: null,
    routes: [{path:'/', name: 'home'},{path:'/data-center', name:'data center'}] 
  }
}

0👍

in the data you return a selected_num param:

data() {
    return {
        selected_num: 0
    }
}

in your template:

 <ul class="nav">
    <li class="nav-item" :class="selected_num===0 ? 'selected' : ''" @click="selected_num=0"><router-link to="/">首页</router-link></li>
    <li class="nav-item" :class="selected_num===1 ? 'selected' : ''" @click="selected_num=1"><router-link to="/data-center">数据中心</router-link></li>
  </ul>

you even do not need the method.

Leave a comment