插槽作用: 父组件 传递 结构 给子组件
插槽使用的2个步骤
第一步: 在子组件中定义一个插槽默认值:如果父组件没有传递则默认显示
第二步: 在父组件中传递结构:<子组件>父组件需要传递的结构</子组件>
一.slot匿名插槽
- 子组件goods.vue
<template>
<div class="son">
<h3>我是子组件</h3>
<h4>商品名称</h4>
<!-- 插槽:可以让父组件决定这里放什么。 也可以设置默认值 -->
<slot>我是默认值</slot>
</div>
</template>
<script>
export default {
name: "goods",
data() {
return {}
}
}
</script>
<style scoped>
.son {
border: 1px solid red;
}
</style>
- 父组件App.vue
<template>
<div id="app">
<h1>我是父组件</h1>
<!-- 子组件1:插入购买链接 -->
<goods>
<button>
<a href="http://www.jd.com">点击购买</a>
</button>
</goods>
<!-- 子组件2:插入禁用点击的按钮 -->
<goods>
<button disabled>已卖完</button>
</goods>
<!-- 子组件3:没有插入内容,则显示默认插槽 -->
<goods></goods>
</div>
</template>
<script>
//导入局部组件
import goods from "./components/goods.vue"
export default {
data() {
return {}
},
components: {
goods
}
}
</script>
<style>
#app {
border: 1px solid #000;
}
</style>
总结:匿名插槽中所使用的的插槽没有"名字",父组件中传递的所有html结构会毫无保留的传递给子组件中的插槽。
二.具名插槽
具名插槽语法:
1.给子组件的添加name属性 : name="插槽名"
- 父组件使用v-slot:插槽名 : 给指定的插槽传递结构
- 注意:这个v-slot指令必须要写在