当前位置:首页 > VUE

vue实现div切换

2026-02-18 05:11:10VUE

Vue 实现 div 切换的方法

使用 v-ifv-else

通过 Vue 的指令 v-ifv-else 可以条件性地切换 div 显示。这种方式会完全销毁和重建 DOM 元素。

<template>
  <div>
    <button @click="toggle">切换显示</button>
    <div v-if="show">内容1</div>
    <div v-else>内容2</div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      show: true
    }
  },
  methods: {
    toggle() {
      this.show = !this.show;
    }
  }
}
</script>

使用 v-show

v-show 通过 CSS 的 display 属性控制显示和隐藏,不会销毁 DOM 元素,适合频繁切换的场景。

vue实现div切换

<template>
  <div>
    <button @click="toggle">切换显示</button>
    <div v-show="show">内容1</div>
    <div v-show="!show">内容2</div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      show: true
    }
  },
  methods: {
    toggle() {
      this.show = !this.show;
    }
  }
}
</script>

使用动态组件 <component>

通过动态组件可以切换不同的组件或模板,适合复杂内容的切换。

vue实现div切换

<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>

使用 CSS 过渡动画

结合 Vue 的 <transition> 组件可以为切换添加动画效果。

<template>
  <div>
    <button @click="show = !show">切换动画</button>
    <transition name="fade">
      <div v-if="show">带动画的内容</div>
    </transition>
  </div>
</template>

<script>
export default {
  data() {
    return {
      show: true
    }
  }
}
</script>

<style>
.fade-enter-active, .fade-leave-active {
  transition: opacity 0.5s;
}
.fade-enter, .fade-leave-to {
  opacity: 0;
}
</style>

使用路由切换

通过 Vue Router 可以实现不同路由对应的视图切换,适合页面级别的切换。

<template>
  <div>
    <router-link to="/page1">页面1</router-link>
    <router-link to="/page2">页面2</router-link>
    <router-view></router-view>
  </div>
</template>

根据具体需求选择合适的方法,v-ifv-show 适合简单内容切换,动态组件和路由适合复杂场景。

标签: vuediv
分享给朋友:

相关文章

vue实现一个标签选择

vue实现一个标签选择

Vue 标签选择组件实现 基础实现 使用 Vue 的 v-for 和 v-model 指令可以快速实现标签选择功能: <template> <div class="tag-se…

vue实现swipe

vue实现swipe

Vue实现Swipe功能的方法 使用第三方库(推荐) Vue生态中有多个成熟的轮播/滑动组件库,例如vue-awesome-swiper或swiper/vue。以下是基于swiper/vue的实现示例…

vue实现pc

vue实现pc

Vue 实现 PC 端应用开发 Vue.js 是一个流行的前端框架,适用于构建 PC 端 Web 应用。以下是关键步骤和最佳实践: 项目初始化 使用 Vue CLI 或 Vite 创建项目:…

vue filter 实现

vue filter 实现

在 Vue.js 中,过滤器(Filter)是一种用于文本格式化的功能,可以在模板中直接使用。以下是实现过滤器的详细方法: 全局过滤器注册 通过 Vue.filter 方法注册全局过滤器,可在所有组…

vue实现反转

vue实现反转

实现数组反转 在Vue中反转数组可以通过多种方式实现,以下是几种常见方法: 使用JavaScript原生reverse方法 // 在methods中定义方法 methods: { revers…

vue rooter 实现原理

vue rooter 实现原理

Vue Router 实现原理 Vue Router 是 Vue.js 官方的路由管理器,用于构建单页面应用(SPA)。其核心实现原理包括路由匹配、组件渲染和导航守卫等机制。 路由匹配与动态路由 V…