vue实现导航切换内容
Vue 实现导航切换内容的方法
使用动态组件 <component :is>
通过 Vue 的 <component :is> 动态绑定组件名,配合 v-for 渲染导航栏,点击切换内容。
<template>
<div>
<nav>
<button
v-for="tab in tabs"
:key="tab.name"
@click="currentTab = tab.name"
>
{{ tab.label }}
</button>
</nav>
<component :is="currentTab" />
</div>
</template>
<script>
import ComponentA from './ComponentA.vue';
import ComponentB from './ComponentB.vue';
export default {
data() {
return {
currentTab: 'ComponentA',
tabs: [
{ name: 'ComponentA', label: '选项A' },
{ name: 'ComponentB', label: '选项B' }
]
};
},
components: { ComponentA, ComponentB }
};
</script>
结合路由(Vue Router)
通过 Vue Router 实现导航与路由的绑定,切换 URL 时自动更新内容。

<template>
<div>
<nav>
<router-link to="/page1">页面1</router-link>
<router-link to="/page2">页面2</router-link>
</nav>
<router-view />
</div>
</template>
路由配置示例:
import Page1 from './views/Page1.vue';
import Page2 from './views/Page2.vue';
const routes = [
{ path: '/page1', component: Page1 },
{ path: '/page2', component: Page2 }
];
条件渲染(v-if/v-show)
通过 v-if 或 v-show 控制不同内容的显示与隐藏。

<template>
<div>
<button @click="activeTab = 'A'">显示A</button>
<button @click="activeTab = 'B'">显示B</button>
<div v-if="activeTab === 'A'">内容A</div>
<div v-if="activeTab === 'B'">内容B</div>
</div>
</template>
<script>
export default {
data() {
return {
activeTab: 'A'
};
}
};
</script>
使用状态管理(Vuex)
通过 Vuex 集中管理导航状态,跨组件共享当前选中项。
// store.js
export default new Vuex.Store({
state: {
currentTab: 'Home'
},
mutations: {
setTab(state, tabName) {
state.currentTab = tabName;
}
}
});
组件中调用:
<template>
<button @click="$store.commit('setTab', 'About')">关于页</button>
</template>
注意事项
- 性能:
v-if会销毁组件,适合低频切换;v-show仅切换 CSS 显示,适合高频切换。 - 路由懒加载:使用
() => import('./Component.vue')提升页面加载速度。 - 动画效果:可通过
<transition>为内容切换添加过渡动画。






