Rendering an array of components using Vue 3's Composition API with TypeScript and the <script setup> syntax can be pretty straightforward. Let's go through a simple example step by step.
Step 1: Setting up a New Vue 3 Project
If you haven't already, create a new Vue 3 project using Vite:
npm init vite@latest my-vue-app -- --template vue-ts
cd my-vue-app
npm install
Step 2: Create a Child Component
First, let's create a child component that we'll render multiple times. Create a file src/components/MyComponent.vue:
<template>
<div class="my-component">
{{ message }}
</div>
</template>
<script setup lang="ts">
import { defineProps } from 'vue';
const props = defineProps<{
message: string;
}>();
</script>
<style scoped>
.my-component {
padding: 10px;
margin-bottom: 10px;
border: 1px solid #ccc;
}
</style>
Step 3: Render an Array of Components
Now, let's use the MyComponent component in our main App.vue file. We will render an array of MyComponent instances with different props.
Update src/App.vue:
<template>
<div id="app">
<h1>Array of Components</h1>
<div v-for="(message, index) in messages" :key="index">
<MyComponent :message="message" />
</div>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import MyComponent from './components/MyComponent.vue';
const messages = ref<string[]>([
'Hello, Vue!',
'This is dynamic!',
'Vue 3 with TypeScript',
'Composition API is cool!'
]);
</script>
<style scoped>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
text-align: center;
margin-top: 60px;
}
</style>
Step 4: Run the Application
Start your development server:
npm run dev
Navigate to http://localhost:3000 (or the port Vite specifies) and you should see an array of MyComponent instances rendered, each displaying a different message.
Explanation
-
Child Component (MyComponent.vue): This component accepts a message prop and displays it.
-
Use in Parent Component (App.vue):
- We import the child component.
- We create a reactive array of messages using the
ref function from Vue's Composition API.
- We use the
v-for directive to iterate over the array of messages, rendering a MyComponent instance for each message in the array, passing the message as a prop.
- The
key attribute ensures Vue can efficiently update the DOM when the list changes.
This setup efficiently leverages Vue 3's Composition API and TypeScript to render dynamic arrays of components.