Vue 项目中:对象遍历与数组遍历展示文案的实践对比

背景:在Vue项目中,若要展示多个样式相同的文案,可借助v-for指令遍历数组或对象来优化代码,下面为你提供两种实现方式。
方法一:遍历数组实现文案展示

<script setup lang="ts">
  import {reactive, onMounted } from 'vue'
 
  const totalInfo = reactive({
    name: '',
    age: undefined
  })

  interface totalDataItem {
    key: keyof typeof totalInfo;
    label: string;
  }

  const totalData: totalDataItem[] = [
    { key: 'name', label: '名称'},
    { key: 'age', label: '年龄'}
  ]


  const init = () => {
    totalInfo.name = 'summer';
    totalInfo.age = 18
  }

  onMounted(() => {
    init()
  })
</script>

<template>
  <div>
    <ul>
      <li v-for="(item, index) in totalData" :key="index">
        <span>{{item.label}}</span>{{ totalInfo[item.key]}}
      </li>
    </ul>
    
  </div>
</template>

<style>
  ul li {
    list-style:none;
    line-height: 30px;
    text-align:left;
  }
</style>

方法二:遍历对象实现文案展示

<script setup lang="ts">
  import {reactive, onMounted } from 'vue'
  import {reactive, onMounted } from 'vue'
 
  const totalInfo = reactive({
    name: '',
    age: undefined
  })

   const totalData = {
    name: {label: '名称'},
    age: {label: '年龄'}
  }

  const init = () => {
    totalInfo.name = 'summer';
    totalInfo.age = 18
  }

  onMounted(() => {
    init()
  })
</script>

<template>
  <div>
    <ul>
      <li v-for="(value, key) in totalData" :key="key">
        <span>{{value.label}}</span>{{ totalInfo[key]}}
      </li>
    </ul>
    
  </div>
</template>

<style>
  ul li {
    list-style:none;
    line-height: 30px;
    text-align:left;
  }
</style>

优化要点总结:

  1. 统一样式处理:借助CSS保证所有文案展示样式一致。
  2. 动态绑定数据:把文案内容从模版里分离出来,存于组件数据中。
  3. 提升可维护性:便于后序新增或修改文案,只需调整数据即可,不用改动模版结构。
  4. 合理设置key值:为v-for提供唯一的key,确保渲染效率。

两种遍历方式都能达到文案的循环展示效果,在实际使用时,依据数据来源来挑选合适的实现方式。

你可能感兴趣的:(vue对象遍历,vue数组遍历,相同文案不同数据结构的遍历)