vue header跟随左侧导航切换
时间: 2023-08-11 19:03:06 浏览: 50
可以通过监听路由变化来实现vue header跟随左侧导航切换。
具体步骤如下:
1. 在左侧导航组件中,监听路由变化,当路由变化时,将当前路由的名称存储到vuex的state中。
2. 在header组件中,通过计算属性获取vuex中存储的当前路由名称,来判断header需要显示哪个标题。
3. 在header组件中,利用vue的transition动画,来实现标题的切换效果。
下面是一个简单的示例代码:
```
// 左侧导航组件
<template>
<div>
<ul>
<li v-for="item in navList" :key="item.name" :class="{ active: item.name === currentRoute }" @click="handleClick(item.name)">
{{ item.title }}
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
navList: [
{ name: 'home', title: '首页' },
{ name: 'about', title: '关于我们' },
{ name: 'contact', title: '联系我们' },
],
};
},
computed: {
currentRoute() {
return this.$store.state.currentRoute;
},
},
methods: {
handleClick(name) {
this.$store.commit('setCurrentRoute', name);
this.$router.push({ name });
},
},
};
</script>
// header组件
<template>
<div>
<transition name="title" mode="out-in">
<h1 v-if="currentRoute === 'home'" key="home-title">首页</h1>
<h1 v-else-if="currentRoute === 'about'" key="about-title">关于我们</h1>
<h1 v-else-if="currentRoute === 'contact'" key="contact-title">联系我们</h1>
</transition>
</div>
</template>
<script>
export default {
computed: {
currentRoute() {
return this.$store.state.currentRoute;
},
},
};
</script>
<style>
.title-enter-active,
.title-leave-active {
transition: all 0.5s;
}
.title-enter,
.title-leave-to {
opacity: 0;
transform: translateY(-20px);
}
</style>
```
在vuex中添加一个名为currentRoute的state和一个名为setCurrentRoute的mutation:
```
// vuex
const state = {
currentRoute: 'home', // 当前路由名称
};
const mutations = {
setCurrentRoute(state, routeName) {
state.currentRoute = routeName;
},
};
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)