在Vue中如何使用插槽

2020-10-12  本文已影响0人  云凡的云凡

很重要,很多第三方的Vue的插件或者模块中都大量的使用了插槽这种特性。
使用场景:Vue父组件向子组件传递dom结构,有两种方法:

1.通过属性传递,缺点:会多出一个div,template 不好用,所以通过content传值,直接使用p标签是有问题的,必须包一个div。传递少还行,当传递很多的时候,代码会很难去阅读。

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>16在Vue中如何使用插槽(slot)</title>
    <script src="./vue.js"></script>
</head>

<body>
    <div id="app">
        <child content='<p>哈哈哈</p>'></child>
    </div>
    <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>
</body>
</html>

2.使用slot可以在父组件向子组件优雅的传递dom结构

image.png
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>16在Vue中如何使用插槽(slot)</title>
    <script src="./vue.js"></script>
</head>
<body>
    <div id="app">
        <child>
            <!-- 1.用子组件时插入一点内容 -->
            <h1>hahaha</h1>
        </child>
    </div>
    <script>
        Vue.component('child', {
            // 2.用<slot></slot>可以显示  <p>hahaha</p>
            // 所以使用插槽会更方便的向子组件插入dom元素
            template: `<div>
                <p>hello</p>
                <slot></slot>
                </div>`
        })
        var vm = new Vue({
            el: '#app'
        })
    </script>
</body>
</html>

slot有新的特性
1.定义默认值,定义在slot标签上
2.具名插槽

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>16在Vue中如何使用插槽(slot)</title>
    <script src="./vue.js"></script>
</head>
<body>
    <div id="app">
        <child>
            <div class="footer" slot="footer">footer</div>
        </child>
    </div>
    <script>
        Vue.component('child', {
            template: `<div>
                <slot name="header"></slot>
                <div class="content">content</div>
                <slot name="footer"></slot>
                </div>`
        })
        var vm = new Vue({
            el: '#app'
        })
    </script>
</body>
</html>

总结:插槽只有一个,而具名插槽有多个,同时具名插槽可以有默认值。。
不传的时候会使用默认值

image.png
上一篇 下一篇

猜你喜欢

热点阅读