vue_组件插槽详述
在使用組件時,在引用的組件標簽中添加內容時,會自動被組件中的模板代替,如【例1】
【例1】
<my-comp>Have a happy Life</my-comp> Vue.component('my-comp',{template:`<div> Life is a shit! </div>` })【結果】
1.插槽的使用
當不想要傳遞給組件的內容被替代,則可以使用組件插槽來解決這個問題,具體使用方法是,在組件模板中添加 <slot> 標簽,當組件渲染時,<slot></slot> 將會被替換為“寫在組件標簽結構中的內容”,如【例2】
【例2】
Vue.component('my-comp',{template:`<div> Life is a shit! <slot></slot> </div>` })【結果】
?【注】
2.編譯作用域
因為父級模板里的所有內容都是在父級作用域中編譯的,子模版里的所有內容都是在子作用域中編譯的,所以插槽不能訪問其所在組件的作用域,而是模板的作用域,如【例3】
【例3】
<my-comp>Hi {{ userName }}, Have a happy Life!</my-comp> //組件 Vue.component('my-comp',{template:`<div><slot></slot> </div>`,data(){return {userName: 'Jony'}} }) //vue實例 const vm = new Vue({el:'#app',data:{userName:'Jim'} })【結果】
3.默認插槽
默認插槽即,若在組件引用時,沒有像其傳遞內容,則使用默認插槽的內容(也稱為后備內容);若在引用時,傳遞了內容,則渲染傳遞的內容,如【例4】
【例4】
組件
Vue.component('my-button',{template:`<button type="submit"><slot>Submit</slot> </button>` })未傳遞內容
<my-button></my-button>【結果】
傳遞內容
<my-button>Hit me</my-button>【結果】
4.具名插槽
(1)具名插槽使用
若在一個組件中需要使用多個插槽,則要使用具名插槽來區分,其使用方式為:在組件中的?<slot> 元素上使用一個特殊的特性 name,利用這個特性可以定義額外的插槽;在引用組件時,需要在 <template>? 元素上使用?v-slot 指令,v-slot 的參數即是特性 name,如【例5】
【注】一個不帶name的 <slot> 會帶有隱含的名字“default”。
【例5】
//組件 Vue.component('my-cmp',{template:`<div class="container"><header><slot name='header'></slot></header><main><slot name='main'></slot></main><footer><slot name='footer'></slot></footer><slot></slot></div>` }) <!-- 組件引用 --> <my-cmp><template v-slot:header><div>header</div></template><template v-slot:main><div>main</div></template><template v-slot:footer><div>footer</div></template><template v-slot:default><div>default</div></template> </my-cmp>?【結果】
【注】v-slot 只能添加在 <template> 上,只有一種情況特殊(介紹如下)
(2)具名插槽的縮寫
<my-cmp><template #header>header</template><template #default>default</template> <template #main>main</template> <template #footer>footer</template> </my-cmp>【注】該縮寫只有在其有參數時可以使用?
?5.作用域插槽
為了能夠讓插槽內容訪問子組件的數據,可以將子組件的數據作為綁定在 <slot> 元素的一個特性(插槽 prop),則在父級作用域中,可以給v-slot帶一個值來定義所提供的插槽 prop 名字,如【例6】
【例6】
//組件 Vue.component('my-comp1',{data(){return {user:{name:'桃花扇J',age:18}}},template:`<div><slot v-bind:user="user"></slot> </div>` }) <my-comp1><template v-slot:default="slotProps">{{ slotProps.user.name }}</template> </my-comp1>?【結果】
(1)獨占默認插槽的縮寫語法
當被提供的內容只有默認插槽時,組件的標簽可以被當作插槽的模板來使用,此時,可以將 v-slot 直接用在組件上,且可以縮寫為以下形式:
<my-comp1 v-slot="slotProps">{{ slotProps.user.name }} </my-comp1>【注】默認插槽的縮寫語法不能和具名插槽混用,會導致作用域不明確,即只要出現多個插槽,就需要為所有的插槽使用完整的基于 <template> 的語法
(2)解構插槽 Prop
使用結構傳入具體的插槽prop會使模板更簡潔
<my-comp1 v-slot="{ user }">{{ user.name }} </my-comp1>根據解構的語法,還可以給 prop 重命名
<my-comp1 v-slot="{ user:person }">{{ person.name }} </my-comp1>總結
以上是生活随笔為你收集整理的vue_组件插槽详述的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: vue_组件_监听组件事件
- 下一篇: defer和async属性详解