创建可以管理外部数据的抽象组件

JavaScript Vue.js

Harry十三

2020-03-17

目前,我将Vuetify用于基本组件,并希望创建可重用的扩展。例如,包含复选框的列表,具有某些功能的数据表列等。

对于这个问题,我将以包含复选框列表为例。我创建了以下名为CheckboxGroup.vue的组件

<template>
  <v-container>
    <v-checkbox
      v-for="(item, index) in items"
      :key="index"
      v-model="item.state"
      :label="item.title"
    ></v-checkbox>
  </v-container>
</template>

<script>
export default {
  props: {
    items: Array,
    required: true
  }
};
</script>

该组件将对象数组作为属性,并为每个条目创建一个复选框。

重要部分是v-model="item.state":label="item.title"大多数情况下,该state属性将具有不同的名称,与该title属性相同

为了进行测试,我创建了一个名为Home.vue的视图文件,其中包含一系列文档。

<template>
  <v-container>
    <CheckboxGroup :items="documents"/>
    <v-btn @click="saveSettings">Save</v-btn>
  </v-container>
</template>

<script>
import CheckboxGroup from "../components/CheckboxGroup";

export default {
  components: {
    CheckboxGroup
  },
  data: function() {
    return {
      documents: [
        {
          id: 1,
          name: "Doc 1",
          deleted: false
        },
        {
          id: 2,
          name: "Doc 2",
          deleted: false
        },
        {
          id: 3,
          name: "Doc 3",
          deleted: true
        }
      ]
    };
  },
  methods: {
    saveSettings: function() {
      console.log(this.documents);
    }
  }
};
</script>

This time title is called name and state is called deleted. Obviously CheckboxGroup is not able to manage the documents because the attribute names are wrong.

How would you solve this problem? Would you create a computed property and rename these attributes? Would be a bad idea I think...

And by the way, is using v-model a good idea? A different solution would be to listen to the changed event of a checkbox and emit an event with the item index. Then you would have to listen for the change in the parent component.

I don't think there is a way to create something like

<CheckboxGroup :items="documents" titleAttribute="name" stateAttribute="deleted"/> 

因为无论如何这都是不好的设计。我希望这是一个非常琐碎的问题,每个Vue开发人员都面临这个问题,因为主要目标应该始终是开发可多次重用的抽象组件。

请记住,此复选框问题仅是示例。这个问题的解决方案也可以解决相同或相似的问题:)

第1877篇《创建可以管理外部数据的抽象组件》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

0个回答

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android