Skip to content
TheChatArchiveThe Chat Archive
gpt-4o-2024-05-13· OpenAIAi2 WildChat-4.8M (AI2)

vue 3, composition api, ts, sctipt setup. Render list of components

  1. User

    vue 3, composition api, ts, sctipt setup. Render list of components

  2. 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 of ChildComponent components.

    <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:

    1. Child Component (ChildComponent.vue): This component takes a single prop item of type { name: string } and displays it.

    2. Parent Component (ParentComponent.vue): This component includes the <ChildComponent> inside a v-for loop to render each item in the items array.

    Points to Note:

    • TypeScript Integration: Both the parent and child components use TypeScript, with the child explicitly defining the type for props.
    • Reactivity: The items array is defined as a reactive array using Vue's reactive function.
    • <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.