Vue实现active点击切换

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
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()方法切换路由。 这样就可以实现点击切换路由并且实现按钮颜色切换了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值