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>
相关推荐
李三岁_foucsli1 分钟前
js中消息队列和事件循环到底是怎么个事,宏任务和微任务还存在吗?
前端·chrome
尽欢i1 分钟前
HTML5 拖放 API
前端·html
xiaominlaopodaren15 分钟前
Three.js 光影魔法:如何单独点亮你的3D模型
javascript
PasserbyX17 分钟前
一句话解释JS链式调用
前端·javascript
1024小神18 分钟前
tauri项目,如何在rust端读取电脑环境变量
前端·javascript
Nano23 分钟前
前端适配方案深度解析:从响应式到自适应设计
前端
古夕28 分钟前
如何将异步操作封装为Promise
前端·javascript
小小小小宇28 分钟前
前端定高和不定高虚拟列表
前端
@一枝梅34 分钟前
vue3 vite.config.js 引入bem.scss文件报错
javascript·rust·vue·scss
古夕39 分钟前
JS 模块化
前端·javascript