如何在 Vuejs v-if 中检查数组元素是否相等?

我在一个 vuejs 项目中工作,我遇到了一个问题来检查一个数字是否等于一个数组元素。我的代码是这样的:

<div v-if="someValue != arrayElement">
   //
   </div>

我的问题是我如何遍历数组以检查 var 'someValue' 是否有相等的值。


哆啦的时光机
浏览 410回答 2
2回答

繁星淼淼

Array.includes(value)如果要测试精确值,可以使用new Vue({&nbsp; &nbsp; data: function() {&nbsp; &nbsp; &nbsp; &nbsp; return {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; value: 3,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; array: [3,4,5,6,7,3]&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; },&nbsp; &nbsp; computed: {&nbsp; &nbsp; &nbsp; &nbsp; isInArray: function() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return this.array.includes(value);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }})或者直接在这样的v-if指令中<span v-if="array.includes(value)"> {{ value }} </span>

浮云间

更好的方法是创建计算属性,按特定值过滤数组。例如:new Vue({&nbsp; data: function() {&nbsp; &nbsp; someValue: 3,&nbsp; &nbsp; array: [3,4,5,6,7,3]&nbsp; },&nbsp; computed: {&nbsp; &nbsp; arrayFiltered() {&nbsp; &nbsp; &nbsp; return this.array.filter(elem => elem === this.someValue);&nbsp; &nbsp; }})在您的 html 中,这可能如下所示:<div v-if="array.includes(someValue)">&nbsp; &nbsp;<div v-for="elem in arrayFiltered" :key="array.indexOf(elem)">&nbsp; &nbsp; &nbsp;{{ elem }}&nbsp; &nbsp;</div>&nbsp;</div>因此,您可以将数组指定为对象数组,例如
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript