在用Vue实现点击切换active,并切换路由时遇到的问题

 想要在vue中实现点击切换active样式,可以使用以下方法:

<li :class="activeClass == index ? 'active':''" v-for="(i,index) in xxx" :key="index" @click="getItem(index)">
    {{xxx.x}}
</li>

 使用这种方法只需要:

  1. 在 data 中增加一个变量 activeClass ,储存当前点击的元素
  2. 在 style 里写上 .active 样式
  3. 点击事件:改变 data 中 activeClass 的值

 这样就能实现点击切换active,相较于非循环实现而言更为方便简洁

但是我想在这个基础上实现 路由的切换 ,就不知道该怎么办了

最后只能选择了以下写法:

<li :class="{active: isActive === 1}" @click="changClass(1)">
    <router-link to="/personal/recent">最近</router-link>
</li>
<li :class="{active: isActive === 2}" @click="changClass(2)">
    <router-link to="/personal/article">文章</router-link>
</li>

然后在点击事件中将 data 中的 isActive 修改为 传入的值

这样写非常麻烦,很笨,代码也显得不简洁,但是暂时还没找到好的方法

先把这个问题放在这(求个解决办法!!!)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Vue中,要实现切换由并且实现按钮颜色切换,需要用到Vue Router和Vue的绑定样式。 首先,需要安装Vue Router: ```bash npm install vue-router --save ``` 然后,在main.js中引入Vue Router和创建一个router实例: ```js import Vue from 'vue' import VueRouter from 'vue-router' import App from './App.vue' Vue.use(VueRouter) const router = new VueRouter({ routes: [ { path: '/', component: Home }, { path: '/about', component: About } ] }) new Vue({ el: '#app', router, render: h => h(App) }) ``` 其中,routes是由表,定义了每个由对应的组件。在这个例子中,'/'径对应Home组件,'/about'径对应About组件。 然后,在App.vue中,可以使用Vue的绑定样式来实现按钮颜色切换: ```html <template> <div> <button :class="{ active: $route.path === '/' }" @click="goHome">Home</button> <button :class="{ active: $route.path === '/about' }" @click="goAbout">About</button> <router-view></router-view> </div> </template> <script> export default { methods: { goHome() { this.$router.push('/') }, goAbout() { this.$router.push('/about') } } } </script> <style> .active { background-color: red; color: white; } </style> ``` 在按钮上使用:class绑定,根据$route.path来判断是否为当前由,如果是则添加样式类'active',实现按钮颜色切换。 同,在按钮的点事件中,使用this.$router.push()方法切换由。 这样就可以实现切换由并且实现按钮颜色切换了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值