嗨朋友!感谢光临我的博客
还没上岸的我 还在努力之中,本文中理解有错的时候还请您指点
本人也很喜欢爬虫 欢迎来到本人的公众号 一起交流
公众号:Linux下撸python
能得指点是晚辈荣幸
絮叨一下
插槽在vue中是很重要的概念
插槽作用:为了让组件更加具有扩展性。抽取共性,保留不同为插槽,让其他组件可以传递自己想展示的标签到预留插槽。
slot
匿名插槽
- 如果有内容就展示在 slot所在的位置
- 如果没有内容也没有影响
- 如果有很多内容会全部展示在 slot所在的位置
插槽内容 以及作用域
-
插槽内容
可以是任何html元素<a href=""> <slot></slot> </a>
-
后备内容
<template id="two"> <a href=""> <slot>这个就是后备内容</slot> </a> </template> <two> </two>
在这样的情况的时候
这个就是后备内容
会进行渲染
如果 插槽提供了内容这个就是后备内容
文本将会被替换掉 -
插槽作用域
父级模板里的所有内容都是在父级作用域中编译的;子模板里的所有内容都是在子作用域中编译的。
具名插槽
// 这是在父组件中写
<p slot="one">这个是第一个插槽</p>
<p slot="two">这个是第二个插槽</p>
// 这是在子组件
<slot name="one"></slot>
- 但是以上这种写法已经不推荐使用
- 在 2.6.0 中,具名插槽和作用域插槽引入了一个新的统一的语法 (即 v-slot 指令)
<!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="/node_modules/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
<one>
<template v-slot:q>123</template>
</one>
</div>
<template id="parent">
<div>
<p>这是父级</p>
<slot name="q"></slot>
<two>
<template v-slot:w></template>
</two>
</div>
</template>
<template id="child">
<div>
<p>这个是子级别</p>
<slot name="w"></slot>
</div>
</template>
<script>
new Vue({
el:"#app",
components:{
one:{
template:"#parent",
components:{
two:{
template:"#child"
}
}
}
}
})
</script>
</body>
</html>
具名插槽个人见解
- 具名插槽需要在父组件中使用
<template v-slot="name 值"></template>
举个例子
<template>
<div>
这个是父组件
<children>
<template v-slot:one>如果这里没有值并且设置了后备内容会直接使用后备内容 如果这里设置了值 那莫就会渲染这部分数据</template>
</children>
</div>
</template>
然后在子组件中 使用<slot name="名字">这个就是插槽啊</slot>
<template>
<div>
这个是子组建啊
<slot name="one">这个就是插槽啊</slot>
</div>
</template>
作用域插槽
有时让插槽内容能够访问子组件中才有的数据是很有用的
// 父组件
<children1>
<template v-slot:default="obj">{{obj.obj.number}}</template>
</children1>
// 子组件
<template>
<div>
<slot :obj="obj">{{obj.str}}</slot>
</div>
</template>
<script>
export default {
data() {
return {
obj:{
str:"这里是子组件才有的内容啊",
number:5200
}
}
},
}
</script>
首先看子组件
官网给出的解释
也就是说 我们需要一个自定义属性 进行传递
<slot :obj="obj">{{obj.str}}</slot>
而 obj 就被成为 插槽prop
这样
我们就可以在父组件中 使用 v-slot:default="obj"
接收
然后进行渲染数据即可
写给看到最后的你
朋友,感谢你看到了最后,新手报道,技术不成熟的地方请多多指点,感谢!
有问题可以私信我、大家一起交流 前端知识 以及 爬虫 python知识。
公众号:Linux下撸python
期待和你再次相遇
愿你学的愉快