'How do I create a reusable component based on a static component using Vue 3
I have recently started with Vue 3 and Headless UI.
I have created a ListBox component which is used in App.vue to show a list of People and is working as intended.
I am looking to turn it into a reusable component for showing lists of both People and Countries.
How can I change my component to be dynamic for both types?
ListBox.vue
<template>
<Listbox v-model="selectedPerson">
<ListboxButton class=" bg-white shadow-sm border-gray-500 border-2 shadow-gray-200 font-bold p-4 text-left rounded-md">
{{ selectedPerson.name }}
</ListboxButton>
<ListboxOptions class="mt-2">
<ListboxOption
as="template" v-slot="{ active }"
v-for="person in people" :key="person"
:value="person">
<li :class="{
'bg-blue-500 text-white p-6': active,
'bg-white shadow-lg p-6 text-black ': !active
}">
{{ person.name }}
</li>
</ListboxOption>
</ListboxOptions>
</Listbox>
</template>
<script setup>
import { ref } from 'vue'
import {
Listbox,
ListboxLabel,
ListboxButton,
ListboxOptions,
ListboxOption,
} from '@headlessui/vue'
const people = [
{ id: 1, name: 'Durward Reynolds' },
{ id: 2, name: 'Kenton Towne' },
{ id: 3, name: 'Therese Wunsch' },
{ id: 4, name: 'Benedict Kessler' },
{ id: 5, name: 'Katelyn Rohan' },
]
const selectedPerson = ref(people[0])
</script>
App.vue:
<template>
<ListBox />
</template>
Solution 1:[1]
You almost did what you want, only thing you need is props.people and countries are instance of your child component DataTable.vue and you want to use them in a parent component App.vue.
DataTable.vue :
<template>
<div id='data-table'>
{{table}}
</div>
</template>
<script>
export default {
.
.
.
props: ['table']
}
</script>
App.vue:
<template>
<data-table table='people' />
<data-table table='countries' />
</template>
And also you have to Define the tables in outside the child component and then pass to the child , the better way to this is using state management like vuex
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | two.X |
