vue v-for 4种引用类型遍历的情况

175 阅读1分钟

在vue开发中通过v-for实现对数据生成ui。常规大部分时间内都是以数组或数组对象为主进行开发 那其他两个类型 set与map呢?又或者说v-for直接使用对象呢?

废话不多说 上代码

map写法


const map = ref<Map<string, string>>(new Map());
for (let index = 0; index < 3; index++) {
  map.value.set(`${index}`, `${index}hahah`);
}
const update = () => {
  map.value.set("1", "dsaad");
};
</script>

<template>
  <div v-for="item in map" :key="item[0]">{{ item[1] }}</div>
  <el-button @click="update">修改</el-button>
</template>
set 内嵌map

const set = ref<Set<Map<string, number>>>(new Set([]));
for (let index = 0; index < 3; index++) {
  set.value.add(new Map([["name", index]]));
}
const update = () => {};
</script>

<template>
  <div v-for="item in set" :key="item.get('name')">{{ item.get("name") }}</div>
  <el-button @click="update">修改</el-button>
</template>
单一set
const set = ref<Set<string>>(new Set([]));
for (let index = 0; index < 3; index++) {
  set.value.add(`${index}哈哈`);
}
const update = () => {
  console.log(set.value);
};
</script>

<template>
  <div v-for="item in set" :key="item">{{ item }}</div>
  <el-button @click="update">修改</el-button>
</template>

至于对象 类似于map键值对映射 获取的第一个参数是值 第二个参数是键

const obj = ref({ name: 1 });

const update = () => {
  console.log(obj.value);
};
</script>

<template>     值      键
  <div v-for="(value, key) in obj" :key="item">{{ item }}</div>
  <el-button @click="update">修改</el-button>
</template>

纯属图一乐()