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>'
})

猜你喜欢

转载自blog.csdn.net/qq_33866063/article/details/89669092
今日推荐