繁体   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