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 分钟前
DOM型XSS案例
前端·安全·web安全·网络安全·xss
程序员鱼皮15 分钟前
前特斯拉 AI 总监:AI 编程最大的谎言,是 “提效”
前端·后端·ai·程序员·开发
Irene199123 分钟前
Vue3 规范推荐的 <script setup> 中书写顺序(附:如何响应路由参数变化)
vue.js·路由
pusheng202527 分钟前
普晟传感2026年新春年会总结与分析
前端·javascript·html
谢尔登28 分钟前
React19事件调度的设计思路
前端·javascript·react.js
Emma_Maria38 分钟前
本地项目html和jquery,访问地址报跨域解决
前端·html·jquery
奋斗吧程序媛43 分钟前
常用且好用的命令
前端·编辑器
2301_796512521 小时前
【精通篇】打造React Native鸿蒙跨平台开发高级复合组件库开发系列:Lazyload 懒加载(懒加载的图片)
前端·javascript·react native·react.js·ecmascript·harmonyos
敲敲了个代码1 小时前
从N倍人力到1次修改:Vite Plugin Modular 如何拯救多产品前端维护困境
前端·javascript·面试·职场和发展·typescript·vite
摘星编程1 小时前
OpenHarmony环境下React Native:Timeline时间轴组件
javascript·react native·react.js