考虑:
<ol class="breadcrumb arr-right">
<li v-for="(url,name, index) in links" v-bind:class=" (index == (links.length -1)) ? 'breadcrumb-item active' : 'breadcrumb-item'">
<a v-bind:href="url">{{ name }}</a>
</li>
</ol>
这里的问题是 links.length
总是 undefined
。由于链接的 undefined
状态,除了三元运算外,这里的所有内容都工作正常。如何从 v-bind
访问 links
?
最佳答案
自 links
是一个 object
, links.length
永远是undefined
因为 object
没有 length
属性(但是 Array
does )。
您可以确定 object
的大小通过它的 key 长度。注意 Object.keys()
给出 Array
的 object
的键,所以你可以使用 Array.prototype.length
在结果上获取对象大小。
const class = index === Object.keys(links).length - 1
? 'breadcrumb-item active'
: 'breadcrumb-item'
class binding 的语法不太正确。 你可以结合object syntax和 array syntax像这样:
<li v-bind:class="[ { 'active': index === Object.keys(links).length - 1 }, 'breadcrumb-item' ]">
或者只使用对象语法:
<li class="breadcrumb-item" v-bind:class="{ 'active': index === Object.keys(links).length - 1 }">
但如果您的目标是设计最后一个 <li>
的样式元素,CSS 中可能有更简单的方法。而不是申请 .breadcrumb-item.active
对于最后一项,使用 :last-of-type
:
.breadcrumb-item:last-of-type {
/* your styles here */
}
关于javascript - 如何让对象在 v-bind 和 v-for 中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55463483/