插槽
利用<slot>标签可以实现 组件 在不同的父组件中 使用 有不同的 html 结构
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="../../vue.js"></script>
</head>
<body>
<div id="app">
<home></home>
</div>
<template id="tql">
<child>
<i>你好</i>
</child>
</template>
</body>
<script>
const Child = {
template: `
<div>
<slot />
<h1>我是child主体内容</h1>
以下地方在 不同组件中使用 内容不一样
<hr width="300">
<!--
slot 是一个占位符
最终 会被 组件自定义标签内容所填充,内容是什么 slot就是什么
-->
</div>
`
}
const Home = {
template: "#tql",
components: {
Child
}
}
Vue.component("home",Home);
const vm = new Vue({
el: "#app",
data: {
}
})
</script>
</html>
具名插槽 (插槽起了名字 有多个插槽)
允许我们定义多个插槽,每个插槽起一个名字,在 嵌套内容可以根据名字 一一对应,从而实现在组件中不同的位置实现自定义的Html样式。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="../../vue.js"></script>
</head>
<body>
<div id="app">
<home></home>
</div>
<template id="tql">
<child>
<i slot="s1">你好</i>
<b slot="s2">Vue.js</b>
</child>
</template>
</body>
<script>
const Child = {
template: `
<div>
<slot name="s1"/>
<h1>我是child主体内容</h1>
以下地方在 不同组件中使用 内容不一样
<hr width="300">
<slot name="s2"/>
<!--
slot 是一个占位符
最终 会被 组件自定义标签内容所填充,内容是什么 slot就是什么
-->
</div>
`
}
const Home = {
template: "#tql",
components: {
Child
}
}
Vue.component("home",Home);
const vm = new Vue({
el: "#app",
data: {
}
})
</script>
</html>