具名插槽和作用域插槽

具名插槽

其實就是在父組件中添加一個 slot='自定義名字' 的屬性,
然后在子組件中的 <slot><slot> 里面添加 name='自定義名字' 即可
如果父組件中有一部分沒有添加 slot 屬性,則此處就是默認的插槽,在子組件中的 <slot></slot> 直接就是使用的父組件的默認插槽部分

即:
任何沒有被包裹在帶有 v-slot 的 <template> 中的內(nèi)容都會被視為默認插槽的內(nèi)容。也就是匿名插槽

<child>
            <template>
                <p>ppppp</p>
            </template>

        </child>

作用域插槽

父組件模板的所有東西都會在父級作用域內(nèi)編譯;子組件模板的所有東西都會在子級作用域內(nèi)編譯。
不過,我們可以在父組件中使用 slot-scope(v-slot) 特性從子組件獲取數(shù)據(jù)
前提是需要在子組件中使用 :data=data 先傳遞 data 的數(shù)據(jù)

我們?yōu)榫呙宀酆妥饔糜虿宀垡肓艘粋€新的統(tǒng)一的語法 (即 v-slot 指令)。它取代了 slotslot-scope 這兩個目前已被廢棄但未被移除

使用

dom中

<slot name="header" :msg="msg" :num="num"></slot>

模板接收數(shù)據(jù):

<template v-slot:header="data">

data是所有數(shù)據(jù)組成的集合

實例:

運行結(jié)果:
111ppppp3
Hello
22222

<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <div id="app">
        <child>
            <template v-slot:header="data">
                <p>{{data.msg}}ppppp{{data.num}}</p>
            </template>
            <template v-slot:footer>
                <p>22222</p> 
            </template>
        </child>
    </div>

    <script src="./js/vue.js"></script>
    <script>
        const child = ({
            data() {
                return {
                    msg: 111,
                    num: 3
                }
            },
            template: `<div>
                <slot name="header" :msg="msg" :num="num"></slot>
                Hello
                <slot name="footer"></slot>
            </div>`
        })
        var vm = new Vue({
            el: '#app',
            data: {

            },
            methods: {},
            components: {
                child
            }
        });
    </script>
</body>

</html>

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容