在開發過程中,我們經常會使用各種ui組件,有的時候需要二次封裝,或者修改樣式,以方便重復使用
以element舉例:
<template> <el-input v-model="_value" /> </template> <script> export default { props: { value: { type: String, default: '' } }, computed: { _value: { get() { return this.value; }, set(val) { this.$emit('input', val); } } } // 其他額外的方法或操作 } </script> <style> </style>
另外一種方式,則是通過render方法,將外部所有的參數原樣傳遞過去
<script> export default { name: `BaseInput`, functional: true, render(createElement, context) { return createElement( `el-input`, { ...context.data, props: { ...context.props }, class: (context.data.staticClass || "") + " base_input", style: { width: context.props.width, ...context.data.staticStyle } }, [ context.slots().default // also pass default slot to child ] ); } }; </script> <style scoped> .base_input >>> .el-input__inner { line-height: 39px; border: none; border-bottom: 1px solid rgba(68, 84, 105, 0.2); border-radius: 0; font-size: 16px; font-family: "Poppins"; font-weight: 400; padding: 0; color: rgba(68, 84, 105, 1); } .base_input >>> .el-input__inner:focus { border-bottom: 1px solid rgba(68, 84, 105, 1); } </style>
[context.slots().default]部分,可以修改為context.children,就可以傳遞所有的slot
如果需要繼承具名插槽
const _slots = context.slots(); _slots.footer ? createElement(_slots.footer[0].tag, { slot: 'footer' }, _slots.footer[0].children) : null
放在default后面即可,但是無法直接使用獲取到的具名插槽,原因依舊不知道
ps:但是遇到過一個奇怪的問題,在封裝ElImage的時候,slot傳遞失敗,最后使用context.parent.$createElement進行創建元素才成功,原因不知道