新手關於 Vue Slot 的理解

本文出自:

http://blog.csdn.net/wyk304443164

看了Vue兩天了,記了不少筆記。基本都是稍微看了下,等項目的時候再搞吧。


下面開始

說實話官網比較難懂,在我一開始看的時候,很懵逼,然後看了這篇

http://blog.csdn.net/sinat_17775997/article/details/52484072

講的真的很好。我都能看懂……(^ ^)

下面來點個人總結:

單個Slot

在children這個標籤裏面放Dom,Vue不會理你,也就是不會顯示,類似React:this.props.children。

//父
<children>  
    <span>12345</span>//這邊不會顯示
</children>

//子
components: {
    children: {
        template: "<button>爲了明確作用範圍,所以使用button標籤</button>"
    }
}

你需要寫成這樣

children: {
    template: "<button><slot></slot>爲了明確作用範圍,所以使用button標籤</button>"  
} 

注意這邊 slot 相當於一個坑,等着父組件給填上,這邊 slot 代表的就是上面的 span

多個Slot

這邊需要加name屬性,說白了,多個Slot就不像上面單個,需要有個對應關係。

父-> slot="name1"
子-> <slot name="name1"
//父
<children>  
    <span slot="name1">12345</span>
</children>

//子
components: {
    children: {
        template: "<button>
                        <slot name="name1"></slot>
                        button標籤
                    </button>"
    }
}

這邊寫了一個name1,如果有多個,就插多個,比較簡單。

作用域

<children>  
    <span slot="first" @click="tobeknow">
     12345
    </span>  
    <span slot="second">56789</span> 
</children>

這邊的@click=”tobeknow”的作用域是 父組件,也就是,不能訪問自組件的方法

父組件模板的內容在父組件作用域內編譯;子組件模板的內容在子組件作用域內編譯

沒有分發時內容的提示

如果父組件與自組件有對應的name。
那麼父組件優先,<slot>xx</slot>,xx不會顯示

如果沒有對應的name
那麼子組件內的<slot>xxx</slot>,xxx 將會被展開,<slot>標籤被刪除。
<div id="app">  
    <children>  
        <span slot="first">【12345】</span>  
        <!--上面這行不會顯示-->  
    </children>  
</div>  
<script>  
    var vm = new Vue({  
        el: '#app',  
        components: {  
            children: {
                template: "<div><slot name='first'><button>【如果沒有內容則顯示我1】</button></slot>爲了明確作用範圍,<slot name='last'><button>【如果沒有內容則顯示我2】</button></slot>所以使用button標籤</div>"  
            }  
        }  
    });  
</script>
說明:
【1name='first'的slot標籤被父組件對應的標籤所替換(slot標籤內部的內容被捨棄);
【2name='last'的slot標籤,因爲沒有對應的內容,則顯示該slot標籤內部的內容。

父組件控制子組件內部的方法

this.$children[0].tohidden = true;
<div id="app">  
    <button @click="toshow">點擊讓子組件顯示</button>  
    <children v-if="abc">  
    </children>  
</div>  
<script>  
    var vm = new Vue({  
        el: '#app',  
        data: {  
            abc: false  
        },  
        methods: {  
            toshow: function () {  
                this.abc = !this.abc;  
            }  
        },  
        components: {  
            children: {
                template: "<div>這裏是子組件</div>"  
            }  
        }  
    });  
</script>  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章