Vue3 动态切换组件component

提供选项式、组合式两种写法实现component的动态切换。

代码如下

javascript 复制代码
<template>
  <h3>测试</h3>
  <button @click="currentTemplate =HelloWorld">切换到HelloWorld</button>
  <button @click="currentTemplate =TheWelcome">切换到TheWelcome</button>
  <button @click="switchComponent(curindex)">switchComponent切换</button>
  
  <br/>
  <component :is="p1 ? HelloWorld : TheWelcome" > </component>
  <br/>
  <component :is="currentTemplate" > </component>

</template>

<script setup>
import { ref} from 'vue'
import HelloWorld from './components/HelloWorld.vue'
import TheWelcome from './components/TheWelcome.vue'

const p1 = true;

const currentTemplate = ref(HelloWorld); //赋值是重点 不能是 ref("HelloWorld")
const curindex = ref(1);


function switchComponent(index) {
  console.log(index);
  curindex.value = index+1;
  if (index%2)
  {
    currentTemplate.value = TheWelcome;
  }
  else
  {
    currentTemplate.value = HelloWorld;
  }
}

</script>

<!-- 
<script>
import HelloWorld from './components/HelloWorld.vue'
import TheWelcome from './components/TheWelcome.vue'

export default {
  name: 'MainIndex',
  components: {
    HelloWorld,
    TheWelcome,
  },
  data() {
    return { 
    currentTemplate: "HelloWorld" //当前组件
    };
  },
  methods: {
    //切换 组件
    toggleTemplate(activeTemplate) {
        console.log("toggleTemplate() "+activeTemplate);
        this.currentTemplate = activeTemplate;
        },
      }
}
</script>  -->



<style scoped>
</style>
相关推荐
无心使然云中漫步4 分钟前
Openlayers调用ArcGis地图服务之五 —— 要素识别(/identify)
前端·arcgis·vue·数据可视化
zhensherlock14 分钟前
Protocol Launcher 系列:Beorg 高效任务管理的协议支持
前端·javascript·typescript·node.js·自动化·github·js
ppandss116 分钟前
JavaWeb从0到1-DAY3.1- Vue(ii)
前端·javascript·vue.js
M ? A16 分钟前
Vue 转 React | VuReact编译工具快速入门
前端·javascript·vue.js·后端·react.js·面试·vureact
qq_4275398319 分钟前
iframe 嵌入预览 PDF ,禁用右键菜单、打印下载按钮不展示
前端·javascript·vue.js·pdf
yu859395821 分钟前
降低OFDM系统PAPR的各种算法及误码率分析
前端·算法
ZC跨境爬虫22 分钟前
跟着 MDN 学 HTML day_3:(表单CSS美化实战与盒子模型三大核心属性详解)
前端·javascript·css·html
非科班Java出身GISer31 分钟前
ArcGIS Maps SDK for JavaScript 5.0 组件化开发指南
javascript·arcgis·components·arcgis js 组件化·arcgis js5.0·arcgis js5.0初始化
张风捷特烈31 分钟前
状态管理大乱斗#05 | Riverpod 源码评析 (中) - 上层建筑
android·前端·flutter