vue-动态组件

本文介绍了在Vue中如何使用动态组件来切换不同组件,特别强调了is属性的作用以及在处理DOM模板时遇到的元素约束问题及其解决方案。通过实例演示了如何在HTML和JavaScript中实现组件的动态选择和渲染。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.当不同的组件之间进行切换的时候,使用动态组件会非常有用

2.动态组件使用一个特殊的属性 is 来实现组件间的切换,is属性的内容值可以为一个已经注册的组件的名字,或者是一个组件的选项对象,此时该组件会根据is属性指定的内容对组件进行渲染显示

<component :is="ComponentName"></component>

3.解析DOM模板的时候需要注意,有些HTML元素,如ul, ol, table, select等,对于哪些元素可以出现在其内部是有严格要求的,而有些元素,如li,tr,option只能出现在某些特定元素的内部,这将会导致使用这些约束元素时出现问题,此时可以使用is这个特殊的属性动态对内容进行指定来解决

// 出错情况: 这里自定义组件child-component组件会被视为无效的内容被提升到外部,导致渲染的最终结果出错
<table>
	<child-component></child-component>
</table>
// 对于以上的这种问题可以修改为以下所示即可解决
<table>
	<tr :is="child-component"></tr>
</table>

案例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>动态组件</title>
    <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/dayjs/1.11.7/dayjs.min.js"></script>
</head>

<body>
    <!-- 父组件 -->
    <div id="app">
        <div id="content">
            <component :is='list[id-1]'></component>
        </div>

        <button @click="chooseContent(1)">首页</button>
        <button @click="chooseContent(2)">列表</button>
        <button @click="chooseContent(3)">个人</button>
        <button @click="chooseContent(4)">新闻</button>
    </div>
</body>
<script>
    // 子组件
    let com1 = Vue.component('index-com', {
        template: '<h1>首页内容---</h1>'
    })
    let com2 = Vue.component('list-com', {
        template: '<h1>列表内容---</h1>'
    })
    let com3 = Vue.component('news-com', {
        template: '<h1>个人内容---</h1>'
    })
    let com4 = Vue.component('me-com', {
        template: '<h1>新闻内容---</h1>'
    })

    let app = new Vue({
        el: "#app",
        data(){
            return{
                id: 1,
                list:['index-com','list-com','news-com','me-com']
            }
        },
        methods: {
            chooseContent: function (id) {
                this.id = id;
            }
        }
    })
</script>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值