javascript - 带有额外 li 的 Vue.js v-for 不呈现

标签 javascript vue.js

我有一个 ul,其中包含来自循环的项目,然后是额外的 li。

<ul>
  <todo-item v-for="(todo,index) in todos" v-bind:todo="todo" :key="index" />
  <li :key='"new_item"'>
    <input placeholder="What needs to be done?" type="text" v-model="new_todo" >
    <button v-on:click="add_todo()">Add</button>
  </li>
</ul>  

这不显示额外的行。但如果我切换它,那么额外的 li 是第一个。

<ul>
  <li :key='"new_item"'>
    <input placeholder="What needs to be done?" type="text" v-model="new_todo" >
    <button v-on:click="add_todo()">Add</button>
  </li>
  <todo-item v-for="(todo,index) in todos" v-bind:todo="todo" :key="index" />
</ul>  

所以我可能在 key 上做错了什么,但我找不到具体是什么。

The whole code is here .

最佳答案

问题是 vue 组件需要一个结束标签,仅使用自闭标签将无法正常工作。

这样试试:

<ul>
  <todo-item v-for="(todo,index) in todos" v-bind:todo="todo" :key="index"></todo-item>
  <li :key='"new_item"'>
    <input placeholder="What needs to be done?" type="text" v-model="new_todo" >
    <button v-on:click="add_todo()">Add</button>
  </li>
</ul>  

来自官方Vue Style Guide :

Components that self-close communicate that they not only have no content, but are meant to have no content. It’s the difference between a blank page in a book and one labeled “This page intentionally left blank.” Your code is also cleaner without the unnecessary closing tag.

Unfortunately, HTML doesn’t allow custom elements to be self-closing - only official “void” elements. That’s why the strategy is only possible when Vue’s template compiler can reach the template before the DOM, then serve the DOM spec-compliant HTML.

关于javascript - 带有额外 li 的 Vue.js v-for 不呈现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50915563/

相关文章:

javascript - 传递给 __defineGetter__ 的函数中 "this"的值是多少

javascript - 如何更新 reducer 中对象的 1 个属性?

javascript - 路点和 Inview,使用通配符选择器跟踪多个元素

vue.js - 在 VueJS 组件混合中使用时,Axios 拦截器无法正常运行

vue.js - 重置 vuetify 步进器

javascript - 甲板上的 VueJS V-For 和引导卡

javascript - 安装 Hook 错误 : "Error: An AuthUI instance already exists

javascript - Angularjs 中始终为真的测试失败——Karma

javascript - 从输入中获取多个值并根据它们的类名添加它们

javascript - 在单行而不是列中显示 Vuetify 卡?