vue 3, composition api, ts, sctipt setup. Render list of components
- User
vue 3, composition api, ts, sctipt setup. Render list of components
- Assistant
Rendering a list of components in Vue 3 using the Composition API and
<script setup>syntax in TypeScript involves creating a parent component that maps over an array of data and renders child components accordingly. Below is an example to help you understand the process:1. Define Your Child Component
First, create a child component, for example
ChildComponent.vue, which will be used to render each item in the list.<template> <div class="child-component"> <p>{{ item.name }}</p> </div> </template> <script setup lang="ts"> import { defineProps } from 'vue'; // Define the props for the component const props = defineProps<{ item: { name: string } }>(); </script> <style scoped> .child-component { border: 1px solid #ccc; padding: 1em; margin: 0.5em; } </style>2. Define Your Parent Component
Next, create a parent component, for example
ParentComponent.vue, that will render the list ofChildComponentcomponents.<template> <div class="parent-component"> <!-- Render list of ChildComponent --> <ChildComponent v-for="item in items" :key="item.id" :item="item" /> </div> </template> <script setup lang="ts"> import { reactive } from 'vue'; import ChildComponent from './ChildComponent.vue'; // Define the items array const items = reactive([ { id: 1, name: 'Item 1' }, { id: 2, name: 'Item 2' }, { id: 3, name: 'Item 3' } ]); </script> <style scoped> .parent-component { display: flex; flex-direction: column; align-items: center; } </style>Explanation:
-
Child Component (
ChildComponent.vue): This component takes a single propitemof type{ name: string }and displays it. -
Parent Component (
ParentComponent.vue): This component includes the<ChildComponent>inside av-forloop to render each item in theitemsarray.
Points to Note:
- TypeScript Integration: Both the parent and child components use TypeScript, with the child explicitly defining the type for props.
- Reactivity: The
itemsarray is defined as a reactive array using Vue'sreactivefunction. <script setup>SFC Syntax: This is a compile-time syntactic sugar introduced in Vue 3.2 for using the Composition API more succinctly.
With this setup, you can easily render a list of components in Vue 3 using the Composition API,
<script setup>syntax, and TypeScript. -