vue实现切换功能
使用 v-show 实现切换功能
v-show 通过控制 CSS 的 display 属性来切换元素的显示状态,适合频繁切换的场景。性能较好,因为只是简单地切换显示/隐藏,不会重新渲染 DOM。
<template>
<div>
<button @click="toggle">切换显示</button>
<div v-show="isVisible">内容区域</div>
</div>
</template>
<script>
export default {
data() {
return {
isVisible: true
}
},
methods: {
toggle() {
this.isVisible = !this.isVisible
}
}
}
</script>
使用 v-if 实现切换功能
v-if 会真正地销毁和重建 DOM 元素,适合不频繁切换的场景。当条件为 false 时,元素会被完全移除。
<template>
<div>
<button @click="toggle">切换显示</button>
<div v-if="isVisible">内容区域</div>
</div>
</template>
<script>
export default {
data() {
return {
isVisible: true
}
},
methods: {
toggle() {
this.isVisible = !this.isVisible
}
}
}
</script>
使用动态组件实现切换
适合在不同组件之间切换的场景,通过 component 标签的 is 属性绑定当前组件名。
<template>
<div>
<button @click="currentComponent = 'ComponentA'">显示组件A</button>
<button @click="currentComponent = 'ComponentB'">显示组件B</button>
<component :is="currentComponent"></component>
</div>
</template>
<script>
import ComponentA from './ComponentA.vue'
import ComponentB from './ComponentB.vue'
export default {
components: {
ComponentA,
ComponentB
},
data() {
return {
currentComponent: 'ComponentA'
}
}
}
</script>
使用路由实现页面切换
适合在不同页面之间切换的场景,通过 Vue Router 管理路由。
// router.js
import { createRouter, createWebHistory } from 'vue-router'
import PageA from './views/PageA.vue'
import PageB from './views/PageB.vue'
const routes = [
{ path: '/page-a', component: PageA },
{ path: '/page-b', component: PageB }
]
const router = createRouter({
history: createWebHistory(),
routes
})
export default router
<!-- App.vue -->
<template>
<div>
<router-link to="/page-a">页面A</router-link>
<router-link to="/page-b">页面B</router-link>
<router-view></router-view>
</div>
</template>
使用 transition 添加切换动画
为切换效果添加过渡动画,提升用户体验。
<template>
<div>
<button @click="toggle">切换</button>
<transition name="fade">
<div v-if="isVisible" class="box">内容区域</div>
</transition>
</div>
</template>
<script>
export default {
data() {
return {
isVisible: true
}
},
methods: {
toggle() {
this.isVisible = !this.isVisible
}
}
}
</script>
<style>
.fade-enter-active, .fade-leave-active {
transition: opacity 0.5s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
.box {
width: 200px;
height: 200px;
background: #eee;
}
</style>
使用 Vuex 管理切换状态
当切换状态需要在多个组件间共享时,可以使用 Vuex 进行状态管理。
// store.js
import { createStore } from 'vuex'
export default createStore({
state: {
isVisible: true
},
mutations: {
toggle(state) {
state.isVisible = !state.isVisible
}
}
})
<!-- ComponentA.vue -->
<template>
<button @click="toggle">切换</button>
</template>
<script>
import { mapMutations } from 'vuex'
export default {
methods: {
...mapMutations(['toggle'])
}
}
</script>
<!-- ComponentB.vue -->
<template>
<div v-show="$store.state.isVisible">内容区域</div>
</template>






