vue如何实现组件切换

一、使用条件渲染 (v-if)

复制代码
<template>
    <div>
        <button @click="currentView = 'ComponentA'">Show Component A</button>
        <button @click="currentView = 'ComponentB'">Show Component B</button>
        <component-a v-if="currentView === 'ComponentA'"></component-a>
        <component-b v-if="currentView === 'ComponentB'"></component-b>
    </div>
</template>
<script>
import ComponentA from './ComponentA.vue';
import ComponentB from './ComponentB.vue';
export default {
    data() {
        return {
            currentView: 'ComponentA'
        };
    },
    components: {
        ComponentA,
        ComponentB
    }
};
</script>

二、使用动态组件 (component)

复制代码
<template>
    <div>
        <button @click="currentView = 'ComponentA'">Show Component A</button>

        <button @click="currentView = 'ComponentB'">Show Component B</button>

        <component :is="currentView"></component>
    </div>
</template>

<script>
import ComponentA from './ComponentA.vue';

import ComponentB from './ComponentB.vue';

export default {
    data() {
        return {
            currentView: 'ComponentA'
        };
    },

    components: {
        ComponentA,

        ComponentB
    }
};
</script>

三、点击按钮切换组件

复制代码
<template>
  <div>
    <button @click="toggleComponent">切换组件</button>
    <div v-if="showComponent">
      <ComponentA />
    </div>
    <div v-else>
      <ComponentB />
    </div>
  </div>
</template>

<script>
import ComponentA from './ComponentA.vue'
import ComponentB from './ComponentB.vue'

export default {
  data() {
    return {
      showComponent: true
    }
  },
  methods: {
    toggleComponent() {
      this.showComponent = !this.showComponent
    }
  },
  components: {
    ComponentA,
    ComponentB
  }
}
</script>

<template>
  <div>
    <button @click="toggleComponent">切换组件</button>
    <transition name="fade">
      <component :is="currentComponent" />
    </transition>
  </div>
</template>

<script>
import ComponentA from './ComponentA.vue'
import ComponentB from './ComponentB.vue'

export default {
  data() {
    return {
      currentComponent: 'ComponentA'
    }
  },
  methods: {
    toggleComponent() {
      this.currentComponent = this.currentComponent === 'ComponentA' ? 'ComponentB' : 'ComponentA'
    }
  },
  components: {
    ComponentA,
    ComponentB
  }
}
</script>

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

.fade-enter,
.fade-leave-to {
  opacity: 0;
}
</style>
相关推荐
DFT计算杂谈3 分钟前
AMSET 设置多核并行计算
java·前端·css·html·css3
花椒技术7 分钟前
AI 协同开发落地复盘:1 小时生成首版后,为什么 Review 和修正又花了 2-3 天
前端·人工智能·架构
万少41 分钟前
万少用9个AI工具,帮朋友完成了一个"不可能"的项目
前端
小小小小宇43 分钟前
Vue `import` 为什么可以异步加载
前端
WMYeah1 小时前
【无标题】
前端·rust·抽奖程序·跨平台抽奖程序
Unbelievabletobe1 小时前
免费外汇api的响应时间在不同时段下的波动分析
大数据·开发语言·前端·python
大哥,带带弟弟1 小时前
Grafana 前端嵌入与 JWT 鉴权实战
前端·grafana
小小小小宇1 小时前
前端 V8 引擎垃圾回收机制与内存问题排查
前端
前端老石人1 小时前
CSS 值定义语法
前端·css
sheeta19981 小时前
Vue 前端基础笔记
前端·vue.js·笔记