在 Uniapp 中,可以使用 JavaScript 的 for 循环来遍历数组或对象中的数据。以下是一个示例:

// 遍历数组
let arr = [1, 2, 3, 4];
for (let i = 0; i < arr.length; i++) {
  console.log(arr[i]);
}

// 遍历对象
let obj = {name: '张三', age: 18};
for (let key in obj) {
  console.log(key + ': ' + obj[key]);
}

在 Uniapp 中,我们通常会将这样的遍历操作放在 methods 中,供组件进行调用。例如:

export default {
  data() {
    return {
      list: ['苹果', '香蕉', '橙子'],
      userInfo: {
        name: '张三',
        age: 18,
        sex: '男'
      }
    }
  },
  methods: {
    // 遍历数组
    forEachList() {
      for (let i = 0; i < this.list.length; i++) {
        console.log(this.list[i]);
      }
    },
    // 遍历对象
    forEachObj() {
      for (let key in this.userInfo) {
        console.log(key + ': ' + this.userInfo[key]);
      }
    }
  }
}

在组件中调用这些方法即可:

<template>
  <div>
    <button @click="forEachList">遍历数组</button>
    <button @click="forEachObj">遍历对象</button>
  </div>
</template>

<script>
import { mapActions } from 'vuex'

export default {
  methods: {
    ...mapActions(['forEachList', 'forEachObj'])
  }
}
</script>
Uniapp 中方法的 for 循环示例 - 数组和对象遍历

原文地址: https://www.cveoy.top/t/topic/lH0g 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录