為每個子元素添加包裝器的Vue 3操作
P粉648469285
P粉648469285 2024-01-02 16:58:52
0
1
860

我有一個表單元件,如下所示:

<form-component>
    <text-component name="test1" />
    <select-component name="test2" />
</form-component>

我需要 FormComponent 才能在每個子項目周圍套用包裝器 div

從上面的程式碼來看,FormComponent 的輸出應該是這樣的:

<form>
    <div class="mb-3">
        <text-component name="test1" />
    </div>

    <div class="mb-3">
        <select-component name="test2" />
    </div>
</form>


#
P粉648469285
P粉648469285

全部回覆(1)
P粉415632319

這是一種解決方法:

const formChildren = [{
  name: 'test1',
  is: TextComponent  
}, {
  name: 'test2',
  is: SelectComponent  
}]
<form-component :children="formChildren" />

FormComponent.vue

<template>
  <form>
    <div 
      v-for="(child, index) in children"
      :key="index"
      class="mb-3"
    >
      <component v-bind="child" />
    </div>
  </form>
</template>
<script setup>
defineProps(['children'])
</script>

這是工作示範 您在評論中提出的建議,循環遍歷 $slots.default() 的內容。

如果您更喜歡用模板語法編寫邏輯,那就是正確的方法,我認為這沒有什麼問題。

我個人更喜歡第一種方法,因為我的傾向是(通常)將模板語法限製到最少。將元件保留在物件或映射結構中使我能夠進行精細控制並自動執行任務,例如:

  • 驗證
  • 活動管理
  • 套用來自配置物件的動態預設值
  • 處理瀏覽器/裝置異常

我的偏好可能來自於在配置驅動的環境中進行了大量工作,其中業務邏輯通常儲存在物件中。用模板語法寫它並沒有什麼問題,但總的來說,我發現它有限制。

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!