如何在vue.js中传递对象道具数组?

时间:2020-02-27 00:46:02

标签: vue.js vuejs2

组件:ToDo.vue:

<template>
    <ol>
      <li v-for="toDo in toDos" :key="toDo.id">{{ toDo.text }}</li>
    </ol>
</template>

<script>
export default {
  name: "ToDo",
  props: {
    toDos: Array
  },
};
</script>

这就是我在App.vue中使用上述组件的方式

<template>
  <div id="app">
    <ToDo v-bind:toDos="[234, 263]"></ToDo>
  </div>
</template>

export default {
  name: "App",
  components: {
    ToDo
  }
};
</script>

当我将此数组与之配合使用时,

<ToDo v-bind:toDos="[234, 263]"></ToDo>

列表项将按预期显示(1. 2.)。但是当我将此数组与

一起使用时
<ToDo v-bind:toDos="[{ id: 0, text: "item 1" }, { id: 1, text: "item 2" }]"></ToDo>

我得到错误。我想念什么?

错误:

  4:11  error    'v-bind' directives require an attribute value                           

                                                     vue/valid-v-bind
  5:20  error    Parsing error: Unexpected end of expression                              

                                                     vue/no-parsing-error
  5:21  error    Parsing error: missing-whitespace-between-attributes                     
                                                                                                                                               vue/no-parsing-error
  5:27  error    Parsing error: unexpected-character-in-attribute-name                                                                                                                                                                   vue/no-parsing-error
  6:20  error    Parsing error: unexpected-character-in-attribute-name                                                                                                                                                                   vue/no-parsing-error
  6:27  error    Parsing error: unexpected-character-in-attribute-name                                                                                                                                                                   vue/no-parsing-error
  7:2   error    Parsing error: unexpected-character-in-attribute-name     

1 个答案:

答案 0 :(得分:1)

您正在用对象内的引号关闭属性

<ToDo v-bind:toDos="[{ id: 0, text: 'item 1' }, { id: 1, text: 'item 2' }]" />

虽然更好的解决方案是将数组保留在对象的数据中,然后绑定到该数组(逻辑部分分离)