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>
相关推荐
fdc20172 分钟前
Avalonia:使用附加属性实现命令与事件的绑定
javascript·windows·microsoft
Mike_jia1 小时前
uuWAF:开源Web应用防火墙新标杆——从工业级防护到智能防御实战解析
前端
掘金安东尼1 小时前
Chrome 17 岁了——我们的浏览器简史
前端·javascript·github
袁煦丞1 小时前
群晖NAS FTP远程文件仓库全球访问:cpolar内网穿透实验室第524个成功挑战
前端·程序员·远程工作
前端小巷子1 小时前
JS 打造动态表格
前端·javascript·面试
excel1 小时前
从卷积到全连接:用示例理解 CNN 的分层
前端
UNbuff_01 小时前
HTML 各种事件的使用说明书
前端·html
Mr. Cao code1 小时前
探索OpenResty:高性能Web开发利器
linux·运维·服务器·前端·nginx·ubuntu·openresty
百思可瑞教育2 小时前
ActiveMQ、RocketMQ、RabbitMQ、Kafka 的全面对比分析
vue.js·分布式·rabbitmq·rocketmq·activemq·北京百思可瑞教育·百思可瑞教育
li35749 小时前
将已有 Vue 项目通过 Electron 打包为桌面客户端的完整步骤
前端·vue.js·electron