<!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的名字"的方式