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>
相关推荐
早起傻一天~G29 分钟前
vue2+element-UI上传文件
javascript·vue.js·ui
机器视觉知识推荐、就业指导38 分钟前
npm 安装/运行报错及解决方案
前端·npm·node.js
摇滚侠40 分钟前
12 移动端 WEB 前端 WEB 开发 HTML5 + CSS3 + 移动 WEB
前端·css3·html5
ez52fF0k842 分钟前
.NET11云原生CI/CD在云原生应用持续集成与交付安全加固
前端·c#·交互
独泪了无痕1 小时前
pnpm依赖管理:从零开始的实践手册
前端·npm·node.js
张风捷特烈1 小时前
状态管理大乱斗#08 | MobX 源码评析 - 透明魔法
android·前端·flutter
i220818 Faiz Ul1 小时前
个人健康系统|健康管理|基于java+Android+微信小程序的个人健康系统设计与实现(源码+数据库+文档)
android·java·vue.js·spring boot·微信小程序·毕设·个人健康系统
mCell1 小时前
HTML:AI 时代的通用表达层
前端·html·aigc
mobº1 小时前
Vue3 +TypeScript 项目总结
前端·javascript·typescript
counterxing4 小时前
我整理了一个免费开发资源目录,还做成了 CLI 和 MCP
前端·agent·ai编程