我有一个 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 上做错了什么,但我找不到具体是什么。
最佳答案
问题是 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/