0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Vue.js】配列・連想配列・Mapのループ

Last updated at Posted at 2024-01-04

はじめに

Vue.jsのComposition APIでの配列・連想配列・Mapのループについてまとめました。

環境

  • Vue.js: 3.3.11
  • TypeScript: 5.3.0

配列

v-for="value in 配列" のように指定します。

<script setup lang="ts">
import {ref} from "vue";

const userList: string[] = ["樫野有香", "西脇綾香", "大本彩乃"];
</script>

<template>
 <ul>
  <li v-for="name in userList" :key="name">
    ユーザー名は{{ name }}
  </li>
 </ul>
</template>

配列に限らずループ文全般にいえることですが、keyはコンポーネントで一意でなければいけません。

keyindex を使用すると入れ替え・更新・削除で順番が変わってしまう可能性があるため、keyname にしています1

なお、indexも使用する場合は、v-for="(value, index) in 配列" のように指定します。

<script setup lang="ts">
import {ref} from "vue";

const userList: string[] = ["樫野有香", "西脇綾香", "大本彩乃"];
</script>

<template>
 <ul>
  <li v-for="(name, index) in userList" :key="name">
    index:{{ index }}のユーザー名は{{ name }}
  </li>
 </ul>
</template>

連想配列

v-for="(value, key) in 連想配列" のように指定します。

<script setup lang="ts">
import {ref} from "vue";

const userListInit: {[key: number] : string} = {
  1: "樫野有香",
  2: "西脇綾香",
  3: "大本彩乃"
};
const userList = ref(userListInit);
</script>

<template>
 <ul>
  <li v-for="(name, id) in userList" :key="id">
    id:{{ id }}のユーザー名は{{ name }}
  </li>
 </ul>
</template>

なお、indexを使用する場合は (value, key, index) の順になります。

Map

v-for="[key, value] in Map" のように指定します。

配列や連想配列と異なり、[]を使いkey, valueの順番が逆なので気を付けてください。

<script setup lang="ts">
import {ref} from "vue";

const userListInit = new Map<number, string>();
userListInit.set(1, "樫野有香");
userListInit.set(2, "西脇綾香");
userListInit.set(3, "大本彩乃");
const userList = ref(userListInit);
</script>

<template>
 <ul>
  <li v-for="[id, name] in userList" :key="id">
    id:{{ id }}のユーザー名は{{ name }}
  </li>
 </ul>
</template>

TypeScriptを使わない場合

以下のように書き換えてください。

- <script setup lang="ts">
+ <script setup>
// 配列
- const userList: string[] = ["樫野有香", "西脇綾香", "大本彩乃"];
+ const userList = ["樫野有香", "西脇綾香", "大本彩乃"];

// 連想配列
- const userListInit: {[key: number] : string} = {
+ const userListInit = {

// Map
- const userListInit = new Map<number, string>();
+ const userListInit = new Map();

参考

  1. 同姓同名を考慮する必要がある場合は、配列ではなく連想配列にしてidを持たせる等の工夫が必要

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?