<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>test</title>
<script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<div id="root">
<counter>
<div>dwqweq</div>
</counter>
<counter>
<button>dwqweq</button>
</counter>
</div>
</body>
<script>
const app = Vue.createApp({
});
app.component('counter', {
template: `
<div>
<slot></slot>
</div>
`
});
const vm = app.mount('#root');
</script>
</html>
- slot不仅可以使用div、button等标签,也可以使用子组件。
- slot也可以设置默认值,如果父组件没传slot里的内容,会子组件显示默认的slot里的值,当然也可以是标签。例如
app.component('counter', {
template: `
<div>
<slot><div>默认值</div></slot>
</div>
`
});
- 具名插槽:用name:"slot的名字",给子组件的slot定义名字,以便于确定slot的使用位置,在父组件里用v-slot:"slot的名字"的方式来使用
- 具名插槽在父组件里使用的时候,不仅可以用v-slot:"slot的名字"的方式,也可以用#"slot的名字"的方式