我有一个带有一系列复选框的 Vue 应用程序,当用户选择一个复选框时,这些复选框将项目添加到数组中。可以选择大约 6 个项目,但是,<div>如果选择了2 个特定项目,我需要透露一个:
如果检查所有元素,则示例数组:
["Apples", "Bananas", "Cucumbers", "Pears", "Peaches", "Strawberries"]
Run Code Online (Sandbox Code Playgroud)
但是,如果 ONLYApples和Pears被选中 AND/OR 如果ApplesORPears被选中,我需要div在视图中为用户显示一组指令。
我试过这个,但没有用:
<div v-if="(selectedProducts.length <= 2) && ( selectedProducts.includes('Apples') || selectedProducts.includes('Pears') )">
...show mycontent...
</div>
Run Code Online (Sandbox Code Playgroud)
在我的 vue 实例中,我已经启动了这样的数据:
data: {
selectedProducts: []
}
Run Code Online (Sandbox Code Playgroud)
编写此逻辑的正确方法是什么?在这种情况下我应该使用 array.every() 方法吗?谢谢你。
小智 7
你可以试试
selectedProducts.indexOf('Apples') !== -1
Run Code Online (Sandbox Code Playgroud)
代替
selectedProducts.includes('Apples')
Run Code Online (Sandbox Code Playgroud)
如果我理解正确,如果同时选择了苹果和梨并且仅选择了两项,或者选择了一项并且产品是苹果或梨,则您想要显示 DIV。
如果这是真的,这里有一个计算可以做到这一点。
computed:{
matched(){
let pears = this.selectedProducts.includes("Pears")
let apples = this.selectedProducts.includes("Apples")
if (this.selectedProducts.length === 2 && pears && apples) return true
if (this.selectedProducts.length === 1 && (apples || pears)) return true
return false
}
}
Run Code Online (Sandbox Code Playgroud)
工作示例:
computed:{
matched(){
let pears = this.selectedProducts.includes("Pears")
let apples = this.selectedProducts.includes("Apples")
if (this.selectedProducts.length === 2 && pears && apples) return true
if (this.selectedProducts.length === 1 && (apples || pears)) return true
return false
}
}
Run Code Online (Sandbox Code Playgroud)
console.clear()
new Vue({
el: "#app",
data:{
products: ["Apples", "Bananas", "Cucumbers", "Pears", "Peaches", "Strawberries"],
selectedProducts: []
},
methods:{
onChange(evt, product){
if (evt.target.checked){
this.selectedProducts.push(product)
} else {
this.selectedProducts.splice(this.selectedProducts.indexOf(product), 1)
}
}
},
computed:{
matched(){
let pears = this.selectedProducts.includes("Pears")
let apples = this.selectedProducts.includes("Apples")
if (this.selectedProducts.length === 2 && pears && apples) return true
if (this.selectedProducts.length === 1 && (apples || pears)) return true
return false
}
}
})Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17312 次 |
| 最近记录: |