Vue2插槽
- Vue2插槽
- 默認插槽
- 子組件代碼(`Child.vue`)
- 父組件代碼(`Parent.vue`)
- 命名插槽
- 子組件代碼(`ChildNamed.vue`)
- 父組件代碼(`ParentNamed.vue`)
- 代碼解釋
Vue2插槽
Vue2插槽
下面為你詳細介紹 Vue 2 里默認插槽和命名插槽的使用方法,包含子組件與父組件代碼的編寫方式。
默認插槽
默認插槽用于在子組件里預留一個位置,方便父組件插入內容。
子組件代碼(Child.vue
)
<template><div><h2>子組件</h2><!-- 默認插槽 --><slot></slot></div>
</template><script>
export default {name: 'Child'
}
</script>
父組件代碼(Parent.vue
)
<template><div><h1>父組件</h1><Child><!-- 插入到子組件的默認插槽 --><p>這是插入到子組件默認插槽的內容</p></Child></div>
</template><script>
import Child from './Child.vue'export default {name: 'Parent',components: {Child}
}
</script>
命名插槽
命名插槽允許在子組件中設置多個插槽,父組件可以依據插槽名稱往特定插槽插入內容。
子組件代碼(ChildNamed.vue
)
<template><div><h2>帶命名插槽的子組件</h2><!-- 命名插槽 --><slot name="header"></slot><p>子組件的主體內容</p><slot name="footer"></slot></div>
</template><script>
export default {name: 'ChildNamed'
}
</script>
父組件代碼(ParentNamed.vue
)
<template><div><h1>使用命名插槽的父組件</h1><ChildNamed><!-- 插入到子組件的 header 插槽 --><template #header><h3>這是插入到子組件 header 插槽的內容</h3></template><!-- 插入到子組件的 footer 插槽 --><template #footer><p>這是插入到子組件 footer 插槽的內容</p></template></ChildNamed></div>
</template><script>
import ChildNamed from './ChildNamed.vue'export default {name: 'ParentNamed',components: {ChildNamed}
}
</script>
代碼解釋
- 默認插槽:子組件里使用
<slot></slot>
定義默認插槽,父組件在使用子組件時,直接在子組件標簽內插入內容,這些內容就會顯示在默認插槽的位置。 - 命名插槽:子組件通過
name
屬性定義命名插槽,像<slot name="header"></slot>
。父組件借助<template #插槽名>
語法把內容插入到對應的命名插槽。
這些示例代碼能夠讓你清晰地理解 Vue 2 中默認插槽和命名插槽的用法。你可以依據實際需求對代碼進行調整和擴展。