vue3实现路由点击颜色切换
时间: 2025-01-25 19:10:58 浏览: 37
在Vue 3中,你可以通过使用Vue Router和自定义组件来实现在路由切换时改变某个元素的颜色。这里是一个简单的示例:
首先,在你的项目里安装Vue Router:`npm install @vue/router`
1. 配置路由:
```javascript
import { createRouter, createWebHistory } from 'vue-router';
import Home from './views/Home.vue'; // 假设这是你要切换颜色的页面
const routes = [
{
path: '/',
name: 'Home',
component: Home,
},
];
const router = createRouter({
history: createWebHistory(),
routes,
});
```
2. 在`Home.vue`组件中,添加一个点击事件监听器,给一个元素绑定动态颜色:
```html
<template>
<div class="home-container">
<button @click="changeColor" :style="{ color: activeColor }">点击切换颜色</button>
</div>
</template>
<script setup>
import { ref } from 'vue';
const activeColor = ref('red'); // 初始颜色
const changeColor = () => {
if (activeColor.value === 'red') {
activeColor.value = 'blue'; // 改变颜色
} else {
activeColor.value = 'red'; // 回到初始颜色或其他颜色
}
};
</script>
<style scoped>
.home-container button {
transition: color 0.5s;
}
</style>
```
在这个例子中,每次点击按钮,`activeColor`变量会从`red`变为`blue`,并利用CSS的`:style`特性实时更新元素的颜色。
阅读全文
相关推荐


















