vue父子組件slot插槽的使用
vue父子組件slot插槽
關于父組件在使用子組件的時候,向子組件插入內(nèi)容的方法
1.創(chuàng)建一個子組件并在vue實例中注冊
這是創(chuàng)建子組件
var testzujian = {
? ? ? ? template:`<div>
? ? ? ? ? ? <span>這是子組件的內(nèi)容</span> ??
? ? ? ? ? ? </div>`
? ? }這是注冊子組件
let vm = new Vue({
?? ?el:'.root',
?? ? components:{
? ? ? ? ? ? testzujian:testzujian
? ? ? ? },
})2.在HTML代碼中使用子組件
<body> ? ? <div class="root"> ? ? ? ? <testzujian></testzujian> ? ? ? ? </div> </body>
3.在vue實例中寫入想要插入到子組件的內(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是一個模板字符串,這個模板字符串里面最外面的div標簽是根目錄,必須存在。
根目錄之下的是已經(jīng)注冊的子組件,也是需要加內(nèi)容的子組件標簽,必須存在
子組件標簽之內(nèi)的也是必須存在的
其上的屬性v-slot綁定了一個名字slotcontent,這個名字可以隨意取,但必須得有
這個標簽里面就用來添加
父組件想要插入子組件的內(nèi)容
4.在子組件的模板中通過一個slot標簽
來引入父組件模板中內(nèi)添加的內(nèi)容
var testzujian = {
? ? ? ? template:`<div>
? ? ? ? ? ? <span>這是子組件的內(nèi)容</span>
? ? ? ? ? ? <slot name="slotcontent">
? ? ? ? ? ? </slot> ? ?
? ? ? ? ? ? </div>`
? ? }這是剛才創(chuàng)建好的子組件,現(xiàn)在在其template的模板中,加入了一個slot標簽,屬性name綁定為剛才中v-slot:綁定的名字,也就是slotcontent
vue插槽v-slot實現(xiàn)父向子傳值
// 子組件代碼
<template>
<div class="child">
<h4>this is child component</h4>
<p>收到來自父組件的消息:
<slot name="child"></slot> <!--展示父組件通過插槽傳遞的{{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>以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Vue-router 類似Vuex實現(xiàn)組件化開發(fā)的示例
本篇文章主要介紹了Vue-router 類似Vuex實現(xiàn)組件化開發(fā)的示例,具有一定的參考價值,有興趣的可以了解一下2017-09-09
解決Vue調(diào)用springboot接口403跨域問題
這篇文章主要介紹了解決Vue調(diào)用springboot接口403跨域問題,本文給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2019-09-09

