尝试理解 v-for 内的 v-bind。

huangapple go评论101阅读模式
英文:

Trying to understand v-bind within v-for

问题

  1. 为什么在:id="this.code + '-' + index"上不需要它?

  2. 当将id更改为以下方式时为什么会出错::id="{this.code+'-'+index}"

    我在控制台中收到以下错误,它抱怨this.code中的点,因此this不在范围内:

    解析JavaScript表达式时出错:意外的标记 '.'。
    
英文:

Take the below code as an example:

.fav { background:blue} 
<li
  v-for="(book, index) in books"
  :key="book.title"
  :id="this.code + '-' + index"
  :class="{fav: book.isFav}"
>
  {{book.title}} - {{index}}
</li>
data() {
  return {
    code: "N54234",
    books: [
      { title: "the final empire", isFav: true },
      { title: "the test empire", isFav: false },
      { title: "the first empire", isFav: true },
    ],
  };
}

Assuming the fav: book.isFav is a ternary operator and the {} in {fav: book.isFav} is a way of grouping similar to a function, then why:

  1. Is it not required on :id="this.code + '-' + index"?

  2. Does it give an error when id is changed to use it like so: :id="{this.code+'-'+index}"

    I get the following error in the console where it complains about the dot in this.code so this is out of scope

    Error parsing JavaScript expression: Unexpected token '.'
    

答案1

得分: 1

我终于明白了我的错误。感谢大家的努力和解释。我误解了JS对象是Vue的一个函数。我现在明白,一个对象被传递给v-bind的:class,然后取isFav的布尔值来确定是否要附加类fav。再次感谢大家分享您的专业知识。

英文:

I finally understand my mistake. Thank you all for your efforts and the clarifications. I misunderstood the JS Object as a function of Vue. I now understand that an object is passed to the v-bind :class and then takes the Boolean value of isFav to determine if the class fav is to be attached or not. Thank you all again for sharing your expertise.

huangapple
  • 本文由 发表于 2023年8月11日 00:02:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/76877490.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定