vue实现点击切换路由并实现按钮颜色切换
时间: 2023-09-12 11:11:12 浏览: 60
在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()方法切换路由。
这样就可以实现点击切换路由并且实现按钮颜色切换了。