首页 > 文章列表 > Vue.component 组件同时加载失败:为什么只显示一个组件?

Vue.component 组件同时加载失败:为什么只显示一个组件?

140 2025-04-10

Vue.component 组件同时加载失败:为什么只显示一个组件?

组件同时加载失败:仅显示一个组件

问题描述:

在 html 代码中同时包含 <header-bar/> 和 <nav-bar/> 两个 vue.component 组件,但只显示 <header-bar/> 组件,<nav-bar/> 组件被忽略。

代码示例:

<div class="content">
    <header-bar/>
    <nav-bar/>
</div>

解决方案:

将 <header-bar/> 和 <nav-bar/> 转换为自闭合组件,即使用 <header-bar></header-bar> 和 <nav-bar></nav-bar> 形式。

修改后的代码:

<div class="content">
    <header-bar></header-bar>
    <nav-bar></nav-bar>
</div>

这样修改是因为 vue.component 组件的默认行为是将其自身和所有子元素视为模板中的插槽内容。因此,将组件作为自闭合元素可以防止其插槽内容覆盖其他组件的插槽内容。

完整的修改代码:

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <script src="https://unpkg.com/vue"></script>
    <title>Document</title>
</head>

<body>
    <div class="content">
        <header-bar></header-bar>
        <nav-bar></nav-bar>
    </div>
</body>

<script>
    Vue.component("header-bar", {
        data: function() {
            return {
                homeHref: 'https://www.cnblogs.com',
                logo: 'https://cn.vuejs.org/images/logo.png',
                title: 'Vue官网图标',
                hotTel: '实例'
            }
        },
        template: `
            <header>
                <div class="heading">
                    <a :href="homeHref" class="logo">
                        <img :src="logo" :alt="title" />
                    </a>
                    <div class="hotphone">
                        <div class="icon"></div>
                        <div class="text">
                            <h2>全国免费加盟热线:</h2>
                            <h1>{{hotTel}}</h1>
                        </div>
                    </div>
                </div>
            </header>
    `
    });
    Vue.component("nav-bar", {
        data: function() {
            var n = 0;
            if (window.navActive) {
                n = window.navActive;
            }
            return {
                navList: [{
                    href: 'https://www.cnblogs.com',
                    title: '博客园'
                }],
                navActive: n
            }
        },
        template: `
        <nav>
            <div class="navbar">
                <template v-for="(nav,index) in navList">
                     <a :href="nav.href" class="navmenu" v-html="nav.title"></a>
                </template>
            </div>
        </nav>
    `,
        mounted: function() {
            $("a.navmenu").eq(this.navActive).addClass("active");
        }
    });

    new Vue({
        el: '.content',
    })
</script>

</html>
来源:1730789548