使用Vue的slot插槽分發父組件內容實現高度復用、更加靈活的組件


寫在前面

之前寫過一篇關於vue實現dialog會話框組件的文章http://www.cnblogs.com/fozero/p/8546883.html
講到了如何實現一個vue對話框組件,其中涉及到了父組件和子組件的通信,這個不用多說,看我之前的文章就能明白,文章最后也說到了,我們可以使用
slot插槽來編寫組件,slot用來分發內容到子組件中,從而實現組件的高度復用,編寫的組件更加靈活。

還是結合對話框的例子,使用slot來實現對話框組件

注冊一個名叫dialog-tip的全局組件

		Vue.component('dialog-tip', {
		    template: '#dialog-tip',
		    props:['dialogShow','message'],
		    data:function(){
                return {
                	content:''
                }
            },
            methods:{
            }
        });

使用templete標簽來定義這個組件

<template id="dialog-tip">
		<div class="dialog_tip" v-if="dialogShow">
			<div class="dialog_tip--mask"></div>
			<div class="dialog_tip--content">
				<div class="dialog_tip--content__txt">
					<slot name="msg">請輸入1-8000之間任意整數</slot>
				</div>
				<div class="dialog_tip--content__btns">
					<slot>
						<button class="btn">確定</button>
						<button class="btn">重新輸入</button>
						<button class="btn">去注冊</button>
					</slot>
				</div>
			</div>
		</div>
	</template>

組件內容包括兩部分 ,一個是提示內容,一個是button按鈕,我們將要修改替換的內容使用slot包含起來,
這樣父組件就可以分發內容到子組件里面了。

<div class="dialog_tip--content__txt">
					<slot name="msg">請輸入1-8000之間任意整數</slot>
				</div>
				<div class="dialog_tip--content__btns">
					<slot>
						<button class="btn">確定</button>
						<button class="btn">重新輸入</button>
						<button class="btn">去注冊</button>
					</slot>
				</div>

除了默認插槽,還可以定義具名插槽 ,如果組件中有好幾個部分內容需要替換,我們可以為它定義一個name,例如:

<slot name="msg">請輸入1-8000之間任意整數</slot>

這樣在使用組件的時候,指定slot的name ,就會將這一部分內容替換掉,而不會替換其他的插槽內容

<p slot="msg">請輸入正確手機號</p>

使用定義好的dialog組件

<dialog-tip message="hello" :dialog-show="dialogShow.tip3">
			<p slot="msg">請輸入正確手機號</p>
			<button class="btn" @click="closeDialogTip('tip3')">確定</button>
		</dialog-tip>
		<dialog-tip message="hello" :dialog-show="dialogShow.tip4">
			<p slot="msg">抱歉,沒有此用戶,請核實后輸入</p>
			<button class="btn" @click="closeDialogTip('tip4')">重新輸入</button>
			<button class="btn" @click="reg">去注冊</button>
		</dialog-tip>

如果不指定slot的名稱,默認dialog-tip標簽里面的內容會替換子組件中使用slot包含的內容部分,例如以上

使用slot指定了它的名稱來替換子組件中的對應的slot部分,而沒有使用slot指定名稱的內容會默認將子組件中
沒有定義具名插槽的部分內容替換掉。

需要注意的是,如果dialog-tip標簽里沒有定義需要分發的內容,那么子組件中會顯示默認的插槽內容

關於更多的slot用法,請移步https://cn.vuejs.org/v2/guide/components-slots.html

最后

效果圖

作者:fozero
聲明:原創文章,轉載請注明出處,謝謝!http://www.cnblogs.com/fozero/p/8974597.html
標簽:vue,slot


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM