vue3-动态组件

动态的显示不同的组件:

实现方法:

  1. 在父组件的数据里面定义一个数据,用来记录当前展示组件名称,例如:currentItem
  2. 定义多个子组件
  3. 父组件里的模板中,添加 component 标签,其中绑定 is 属性:
<component :is="currentItem"></component>

这句代码等价于:

<input-item v-show="this.currentItem === 'input-item'" />
<img-item v-show="this.currentItem === 'img-item'" />

两者效果一样,上面的写法更精简
4. 如果希望切换组件时,保留组件切换前的状态,可以使用 <keep-alive> 标签,将
<component></component> 包裹起来

示例:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://unpkg.com/vue@next"></script>
    <style>
        img {
            width: 200px;
            height: 200px;
        }
    </style>
</head>

<body>
    <div id="root">
</body>
<script>
    const app = Vue.createApp({
        data() {
            return {
                currentItem: "input-item"
            }
        },
        methods: {
            handleClick() {
                if (this.currentItem === "input-item") {
                    this.currentItem = "img-item";
                } else {
                    this.currentItem = "input-item";
                }
            }
        },
        template: `
            <button @click="handleClick">切换</button>
            <keep-alive>
                <component :is="currentItem"></component>
            </keep-alive>
        `
    });

    app.component('input-item', {
        template: `
            <input type="text" placeholder="请输入今天的天气" />
        `
    });

    app.component('img-item', {
        template: `
        <img src="images/头像3.jpg">
        `
    });

    // 将Vue实例挂载到 id 名为 root 的 dom节点
    app.mount('#root');
</script>

</html>

页面效果:

动态组件.gif

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值