目录
插槽简介
vue通过插槽和具名插槽可以向子组件传递dom元素,子组件可以在template通过<slot>标签引用即可。
示例代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>插槽slot</title>
<script type="text/javascript" src="js/vue.js" ></script>
</head>
<body>
<div id="app">
<child>
<!-- 向子组件child传递dom元素-->
<h1>h1 title</h1>
</child>
<body-component>
<!-- 向子组件传递多个dom元素 通过slot属性区分(具名插槽slot)-->
<div slot='header'>header</div>
<div slot='footer'>footer</div>
</body-component>
</div>
<script>
//子组件child使用<slot></slot>接收外部传入的dom元素
Vue.component('child',{
template: `<div>
<p>content</p>
<slot><p>默认dom<p></slot>
</div>`
})
//子组件用<slot></slot>接收外部传入的多个元素,使用name区分具名slop
Vue.component('body-component',{
template: `<div>
<slot name='header'></slot>
<p>body content</p>
<slot name='footer'></slot>
</div>`
})
var app = new Vue({
el: '#app'
})
</script>
</body>
</html>