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>
相关推荐
dcmfxvr4 小时前
【无标题】
java·linux·前端
无巧不成书02185 小时前
React Native 深度解析:跨平台移动开发框架
javascript·react native·react.js·华为·开源·harmonyos
SoaringHeart5 小时前
Flutter 顶部滚动行为限制实现:NoTopOverScrollPhysics
前端·flutter
zhanglu51165 小时前
Java Lambda 表达式使用深度解析
开发语言·前端·python
全栈前端老曹5 小时前
【Redis】发布订阅模型 —— Pub/Sub 原理、消息队列、聊天系统实战
前端·数据库·redis·设计模式·node.js·全栈·发布订阅模型
广州华水科技5 小时前
单北斗GNSS变形监测系统应用与安装指南
前端
coding随想5 小时前
深入Modernizr源码:揭秘CSS伪类检测的底层逻辑
前端·css
奋斗吧程序媛5 小时前
vue3初体验(1)
前端·javascript·vue.js
C澒5 小时前
前端校验 + 交互优化:驿站自取件入库流程效率跃升实践
前端·状态模式·交互·教育电商·交通物流
资深web全栈开发5 小时前
设计模式之桥接模式 (Bridge Pattern)
javascript·设计模式·桥接模式