
组件同时加载失败:仅显示一个组件
问题描述:
在 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>以上就是Vue.component 组件同时加载失败:为什么只显示一个组件?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号