您的位置:首页 > Web前端 > Vue.js

vue学习笔记之slot插槽基本用法实例分析

2020-02-13 11:30 671 查看

本文实例讲述了vue学习笔记之slot插槽基本用法。分享给大家供大家参考,具体如下:

不使用插槽,在template中用v-html解析父组件传来的带有标签的content

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
<child content="<p>Rachel</p>"></child>
</div>
</body>
</html>
<script>
Vue.component('child', {
props: ['content'],
template: '<div>
<p>hello</p>
<div v-html="this.content"></div>
</div>'
})
var vm = new Vue({
el: '#app'
})
</script>

使用插槽,如果父组件为空,就会显示slot中定义的默认内容

<child>
<p>Rachel</p>
</child>
Vue.component('child', {
template: '<div>
<p>hello</p>
<slot>默认内容</slot>
</div>'
})

使用插槽添加header和footer,使用‘具名插槽',也就是给插槽起个名字,各找各的位置。此处也可以写默认值,如果父组件没有对应的插槽内容的话,会显示子组件定义的插槽的默认值。

<div id="app">
<body-content>
<div class="header" slot="header">header</div>
<div class="footer" slot="footer">footer</div>
</body-content>
</div>
Vue.component('body-content', {
template: '<div>
<slot name="header">default header</slot>
<div class="content">content</div>
<slot name="footer">default footer</slot>
</div>'
})

感兴趣的朋友可以使用在线HTML/CSS/JavaScript代码运行工具http://tools.jb51.net/code/HtmlJsRun测试上述代码运行效果。

希望本文所述对大家vue.js程序设计有所帮助。

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  vue slot插槽