uniapp 动态提取数据:从多层嵌套数组中获取品牌、配置信息

假设数据存储在 data 变量中,我们可以使用以下代码动态提取 inputs 里的品牌->小米->8+128:

<template>
  <div>
    <p>品牌:{{brand}}</p>
    <p>配置:{{config}}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      inputs: [
        {
          name: '品牌',
          price: '',
          values: [
            {
              name: '小米',
              price: '',
              values: [],
            },
            {
              name: '',
              price: '',
              values: [],
            },
          ],
        },
        {
          name: '配置',
          price: '',
          values: [
            {
              name: '8+128',
              price: '',
              values: [],
            },
          ],
        },
        {
          name: '',
          price: '',
          values: [
            {
              name: '',
              price: '',
              values: [],
            },
          ],
        },
      ],
      brand: '',
      config: '',
    };
  },
  mounted() {
    // 提取品牌->小米->8+128
    this.brand = this.inputs[0].values[0].name;
    this.config = this.inputs[1].values[0].name;
  },
};
</script>

mounted 生命周期钩子中,我们使用 inputs 数组的索引来获取数据。如果我们想要动态提取数据,可以使用 v-for 指令来循环 inputs 数组,然后在模板中动态绑定数据。例如:

<template>
  <div>
    <p v-for="(input, index) in inputs" :key="index">
      {{ input.name }}:
      <span v-if="input.values.length > 0">{{ input.values[0].name }}</span>
    </p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      inputs: [
        {
          name: '品牌',
          price: '',
          values: [
            {
              name: '小米',
              price: '',
              values: [],
            },
            {
              name: '',
              price: '',
              values: [],
            },
          ],
        },
        {
          name: '配置',
          price: '',
          values: [
            {
              name: '8+128',
              price: '',
              values: [],
            },
          ],
        },
        {
          name: '',
          price: '',
          values: [
            {
              name: '',
              price: '',
              values: [],
            },
          ],
        },
      ],
    };
  },
};
</script>

上面的代码将循环 inputs 数组,并在模板中动态绑定品牌和配置数据。如果 input.values 数组的长度大于 0,我们将显示第一个元素的名称。


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

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