一.匿名插槽
在这个案例里面的分析
1.插槽可以很方便的替换内容
2.在app.vue中child组件内可以使用app中data的数据
child.vue
<template> <div> <a :href="myUrl"> <slot></slot> </a> </div> </template> <script> export default { name: "", props: ["myUrl"], data() { return {}; }, components: {}, }; </script> <style scoped></style>
App.vue
<template>
<div>
<h1>插槽</h1>
<child :url="url">
百度的链接地址为:{{url}}
</child>
</div>
</template>
<script>
import child from "./components/Child.vue";
export default {
data() {
return {
isShow: false,
url: "https://www.baidu.com.cn",
};
},
components: {
child,
},
};
</script>
<style>
div {
text-align: center;
}
</style>
二.具名插槽
child.vue
<template> <div> <header> <slot name="header">11111</slot> </header> <main> <slot>22222</slot> </main> <footer> <slot name="footer">33333</slot> </footer> </div> </template> <script> export default { name: "", data() { return {}; }, components: {}, }; </script> <style scoped></style>
App.vue
<template> <div> <h1>插槽</h1> <child> <div slot="header"> <h2>这是头部的具名插槽</h2> </div> <div> <h2>匿名插槽</h2> </div> <div slot="footer"> <h2>这是底部的具名插槽</h2> </div> </child> </div> </template> <script> import child from "./components/Child.vue"; export default { data() { return { isShow: false, url: "https://www.baidu.com.cn", }; }, components: { child, }, }; </script> <style> div { text-align: center; } </style>
三.版本写法
2.6版本后的插槽的写法 与 语法糖
1.标签一定要是 template
2.使用v-slot:插槽名
3.语法糖: 可以将 v-slot: header 改为 #header
4.父取子的插槽变量,仅限对应的插槽内使用
App.vue
<template> <div> <h1>插槽</h1> <child> <!-- <div slot="header"> --> <template v-slot:header> <h2>这是头部的具名插槽</h2> </template> <div> <h2>匿名插槽</h2>
{{ msg }} // 这里的内容不存在,也就不会出现信息,说明了即使是获取到子组件的信息,但也是插槽内部一一对象的 </div> <template v-slot:footer> <h2>这是底部的具名插槽</h2> </template> </child> </div> </template> <script> import child from "./components/Child.vue"; export default { data() { return { isShow: false, url: "https://www.baidu.com.cn", }; }, components: { child, }, }; </script> <style> div { text-align: center; } </style>
四.插槽的作用域
1.主要是父组件怎么去访问子组件的内容呢?
child.vue
<template> <div> <header> <slot name="header" :msg="msg">11111</slot> </header> <main> <slot>22222</slot> </main> <footer> <slot name="footer" :msg="msg">33333</slot> </footer> </div> </template> <script> export default { name: "", data() { return { msg: "张三", }; }, components: {}, }; </script> <style scoped></style>
app.vue
<template> <div> <h1>插槽</h1> <child> <!-- <div slot="header"> --> <template #header="{msg}"> <!-- 语法糖的写法 --> <h2>这是头部的具名插槽---{{ msg }}----</h2> <!-- 用到了对象的结构 --> </template> <div> <h2>匿名插槽</h2> </div> <template v-slot:footer="obj"> <!-- 用到了2.6版本之前的写法 --> <h2>这是底部的具名插槽----{{ obj.msg }}----</h2> <!-- 子组件通过插槽定义的变量传给父组件本身就是对象,通过对象获取相应的属性 --> </template> </child> </div> </template> <script> import child from "./components/Child.vue"; export default { data() { return { isShow: false, url: "https://www.baidu.com.cn", }; }, components: { child, }, }; </script> <style> div { text-align: center; } </style>