3 回答
TA貢獻1785條經驗 獲得超4個贊
我在Vue上學到的一個便宜技巧是,如果模板中需要安裝模板時未加載的任何內容,則只需在模板上放置v-if:
<template v-if="$refs">
<div ref="div1" :style="{ maxHeight: getMaxHeight($refs.div1) }"></div>
</template>
周圍。乍一看可能很臟,但事實是,它可以完成工作,而不會增加額外的代碼和時間,并避免了錯誤。
此外,您的expandable-函數的代碼長度也有小幅改進:
const expandable = el => el.style.maxHeight =
( el.classList.contains('expanded') ?
el.children.map(c=>c.scrollHeight).reduce((h1,h2)=>h1+h2)
: 0 ) + 'px';
TA貢獻1794條經驗 獲得超8個贊
制作直接在div元素上運行的自定義指令可能是您的最佳選擇。您可以創建一個指令組件,例如:
export default {
name: 'maxheight',
bind(el) {
const numberOfChildren = el.children.length;
// rest of your max height logic here
el.style.maxHeight = '100px';
}
}
然后只需確保將指令導入您計劃使用的文件中,并將其添加到div元素中:
<div ref="div1" maxheight></div>
添加回答
舉報
