vue3在js中循环数组
时间: 2024-11-09 07:28:09 浏览: 42
Vue3中的数组循环通常通过模板语法或Composition API来实现。以下是两种常见方法:
1. 模板语法 (HTML + JS):
```html
<template>
<div v-for="(item, index) in items" :key="index">
{{ item }} - 这是索引{{ index }}
</div>
</template>
<script setup>
import { ref } from 'vue';
const items = ref([1, 2, 3, 4, 5]);
</script>
```
在这个例子中,`v-for`指令用于遍历数组`items`,`key`属性用来确保每个元素的唯一标识。
2. Composition API (setup语法):
```html
<template>
<ul>
<li v-for="item, index in $iterable(items)" :key="index">{{ item }}</li>
</ul>
</template>
<script setup>
import { reactive, iterate } from 'vue';
const items = reactive([1, 2, 3, 4, 5]);
function* iterable(array) {
for (let i = 0; i < array.length; i++) {
yield array[i], i;
}
}
</script>
```
这里使用了`reactive`函数创建响应式数组,然后通过自定义迭代器`iterate`实现了同样的遍历效果。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)