簡體   English   中英

在 vue.js 中創建可重用組件

[英]create a reusable component in vue.js

如何使我的 vue.js 組件更加通用和可重用並且只能傳遞必要的數據?

這就是我想要構建的:

在此處輸入圖像描述

結構:

  • 該組件有一個 header
  • 組件有不同的輸入
  • 該組件有一個提交按鈕
  • 該組件有一個列表作為頁腳 - 根據輸入傳遞

我的方法

父母

// App.vue
<template>
  <div>
    <!-- Component A -->
    <SettingsCard
     :listA="listA"
     cardType="CompA"
    >
     <template v-slot:header>
       Foo - Component A
     </template>
    </SettingsCard>

    <!-- Component B -->
    <SettingsCard
     :listB="listB"
     cardType="CompB"
    >
     <template v-slot:header>
       Bar - Component B
     </template>
    </SettingsCard>
  </div>
</template>

孩子:

// SettingsCard.vue
<template>
  <div>
    <slot name="header"></slot>

    <div v-if="cardType === 'CompA'">
     <!-- Show input and submit button for component a -->
    </div>

    <div v-if="cardType === 'CompB'">
     <!-- Show input and submit button for component b -->
    </div>

    <ListComponent
     :cardType="cardType"
     :list="computedList"
    />
  </div>
</template>

<script>
export default {
  props: {
    cardType: String, // for the v-if conditions
    listA: Array,
    ListB: Array
  },
  data() {
   return {
      namefromCompA: '', // input from component A
      namefromCompB: ''  // input from component B
    }
  },
  computed: {
    computedList() {
      // returns an array and pass as prop the the card footer
    }
  }
}
</script>

問題

  1. 我的 SettingsCard.vue 組件中有undefined的道具和unused的數據
// CompA:
props: {
 cardType: 'compA',
 listA: [1, 2, 3], // comes from the parent
 listB: undefined // how to prevent the undefined?
}
// CompA:
data() {
  return {
    namefromCompA: 'hello world',
    namefromCompB: '' // unused - please remove me
  }
}
  1. 使用v-if="cardType === 'compA'"感覺不對

您是否有更好的方法來使該組件可重用並刪除任何不必要的東西?

使用方法而不是"cardType === 'CompA'"

只需在您的SettingsCard.vue中嘗試此操作

methods: {
    showMeWhen(type) {
      return this.cardType === type;
    },
  },
}

你的 v-if 渲染條件就像: v-if="showMeWhen('compA')"


更新

例如你的namefromCompA/B你可以傳遞一個新的道具來顯示正確的名字。

props: {
    cardType: String, // for the v-if conditions
    listA: Array,
    ListB: Array,
    namefromComponent: {
        type: String,
        default: 'NoName'
    }
  },

然后在您的使用中,您只需像使用其他道具一樣傳遞它。

<SettingsCard
     :listB="listB"
     cardType="CompB"
     namefrom-component="my Name for component B"
    >

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM