微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在 vue.js 中创建一个可重用的组件 父母孩子:

如何解决在 vue.js 中创建一个可重用的组件 父母孩子:

如何让我的 vue.js 组件更加通用和可重用,并且只能传递必要的数据?

这就是我想要构建的:

enter image description here

结构:

  • 组件有一个标题
  • 组件有不同的输入
  • 组件有一个提交按钮
  • 组件有一个列表作为页脚 - 根据输入传递

我的方法

父母

// 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"
    >

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?