【问题标题】:What is the proper syntax for passing an array of objects and looping through it in Vue3在Vue3中传递对象数组并循环遍历它的正确语法是什么
【发布时间】:2021-09-27 06:59:58
【问题描述】:

我正在尝试创建以下功能

1 个问题数组在 vue 链接中作为道具传递,就像这样

<router-link
          :to="{
            name: 'finder_step',
            params: {
              id: 2,
              questions: [
                {
                  id: 'q1',
                  body: 'one'
                },
                {
                  id: 'q2',
                  body: 'two'
                }
              ]
            }
          }"
        >
          Step 2
</router-link>

其中 questions 属性是一个带有 id 和正文的对象数组。但是,我遇到的问题是我的输出变成了 [ "[object Object]", "[object Object]" ]

我的理解是我的对象在某个时候被转换为字符串。我不明白为什么,以及我需要使用的正确语法是什么。

这是我在 vue 文件中循环数组的方式。

<template>
  <div>
    <p>ID: {{ id }}</p>
    <p>Question: {{ questions }}</p>
    <li
      v-for="question in questions"
      :key="question.id"
    >
      {{ question.body }}
    </li>
  </div>
</template>
<script>
export default {
  props: {
    id: { type: String, default: '' },
    questions: {
      type: Array,
      id: String,
      body: String
    }
  }
}
</script>

【问题讨论】:

  • 如果在子组件中删除 id: String, body: String 并设置 default: () =&gt; [] 会发生什么?

标签: javascript vue.js vue-router vuejs3 laravel-mix-vue3


【解决方案1】:

路由参数旨在成为dynamic path parameters 的路由 URL 中的字符串,因此 Vue Router 会自动 encodes them

一种解决方法是在任何不是字符串/数字的参数上使用JSON.stringify(即,在这种情况下为questions):

<router-link
    :to="{
      name: 'finder_step',
      params: {
        id: 2,            ?  
        questions: JSON.stringify([
          {
            id: 'q1',
            body: 'one'
          },
          {
            id: 'q2',
            body: 'two'
          }
        ])
      }
    }"
  >
    Step 2
</router-link>

然后将JSON.parse 组件中的道具作为computed property

export default {
  props: {
    questions: Array
  },
  computed: {
    computedQuestions() {
      if (typeof this.questions === 'string') {
        return JSON.parse(this.questions)
      } else {
        return this.questions
      }
    }
  }
}

并在模板中使用计算的道具:

<ul>
  <li
    v-for="question in computedQuestions"
    :key="question.id"
  >
    {{ question.body }}
  </li>
</ul>

demo

【讨论】:

    猜你喜欢
    • 2016-09-07
    • 1970-01-01
    • 2013-12-12
    • 1970-01-01
    • 2017-05-13
    • 1970-01-01
    • 2019-12-17
    • 2016-08-09
    • 1970-01-01
    相关资源
    最近更新 更多