vue父子組件slot插槽的使用
vue父子組件slot插槽
關(guān)于父組件在使用子組件的時(shí)候,向子組件插入內(nèi)容的方法
1.創(chuàng)建一個(gè)子組件并在vue實(shí)例中注冊(cè)
這是創(chuàng)建子組件
var testzujian = {
? ? ? ? template:`<div>
? ? ? ? ? ? <span>這是子組件的內(nèi)容</span> ??
? ? ? ? ? ? </div>`
? ? }這是注冊(cè)子組件
let vm = new Vue({
?? ?el:'.root',
?? ? components:{
? ? ? ? ? ? testzujian:testzujian
? ? ? ? },
})2.在HTML代碼中使用子組件
<body> ? ? <div class="root"> ? ? ? ? <testzujian></testzujian> ? ? ? ? </div> </body>
3.在vue實(shí)例中寫入想要插入到子組件的內(nèi)容
let vm = new Vue({
? ? ? ? el:'.root',
? ? ? ? components:{
? ? ? ? ? ? testzujian:testzujian
? ? ? ? },
? ? ? ? template:`<div>
? ? ? ? ? ? <testzujian>
? ? ? ? ? ? ? ? <template v-slot:slotcontent>
? ? ? ? ? ? ? ? ? ? <span>這是父組件向子組件插入的內(nèi)容</span> ? ?
? ? ? ? ? ? ? ? </template>?
? ? ? ? ? ? </testzujian>
? ? ? ? ? ? </div>`,
? ? })其中template是一個(gè)模板字符串,這個(gè)模板字符串里面最外面的div標(biāo)簽是根目錄,必須存在。
根目錄之下的是已經(jīng)注冊(cè)的子組件,也是需要加內(nèi)容的子組件標(biāo)簽,必須存在
子組件標(biāo)簽之內(nèi)的也是必須存在的
其上的屬性v-slot綁定了一個(gè)名字slotcontent,這個(gè)名字可以隨意取,但必須得有
這個(gè)標(biāo)簽里面就用來(lái)添加
父組件想要插入子組件的內(nèi)容
4.在子組件的模板中通過(guò)一個(gè)slot標(biāo)簽
來(lái)引入父組件模板中內(nèi)添加的內(nèi)容
var testzujian = {
? ? ? ? template:`<div>
? ? ? ? ? ? <span>這是子組件的內(nèi)容</span>
? ? ? ? ? ? <slot name="slotcontent">
? ? ? ? ? ? </slot> ? ?
? ? ? ? ? ? </div>`
? ? }這是剛才創(chuàng)建好的子組件,現(xiàn)在在其template的模板中,加入了一個(gè)slot標(biāo)簽,屬性name綁定為剛才中v-slot:綁定的名字,也就是slotcontent
vue插槽v-slot實(shí)現(xiàn)父向子傳值
// 子組件代碼
<template>
<div class="child">
<h4>this is child component</h4>
<p>收到來(lái)自父組件的消息:
<slot name="child"></slot> <!--展示父組件通過(guò)插槽傳遞的{{message}}-->
</p>
</div>
</template>
//父組件代碼
<template>
<div class="parent">
<h3>this is parent component</h3>
<input type="text" v-model="message" />
<Child>
<template v-slot:child>
{{ message }} <!--插槽要展示的內(nèi)容-->
</template>
</Child>
</div>
</template>
<script>
import Child from './child'
export default {
name: 'Parent',
data() {
return {
message: '內(nèi)容',
}
},
components: {
Child,
},
}
</script>以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
vue axios post發(fā)送復(fù)雜對(duì)象問(wèn)題
現(xiàn)在vue項(xiàng)目中,一般使用axios發(fā)送請(qǐng)求去后臺(tái)拉取數(shù)據(jù)。這篇文章主要介紹了vue axios post發(fā)送復(fù)雜對(duì)象的一點(diǎn)思考,需要的朋友可以參考下2019-06-06
vue3響應(yīng)式Object代理對(duì)象的讀取示例詳解
這篇文章主要為大家介紹了vue3響應(yīng)式Object代理對(duì)象的讀取示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-08-08
vue-cli3使用postcss-plugin-px2rem方式
這篇文章主要介紹了vue-cli3使用postcss-plugin-px2rem方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-07-07

