当一个按钮被点击时,我希望将它的name推入一个数组。当按钮没有被点击时,我想从数组中删除它的name。
我知道如何使用推送/拼接数组的@click来做到这一点。
我想知道是否有一种简单的方法可以将按钮的点击绑定到数组,就像v-model中的checkbox一样。我知道你不能在button上使用v-model,但如果我们要让button成为它自己的组件,并在上面使用v-model……
<custom-button v-model="myArray"></custom-button>
有没有办法做到这一点呢?
发布于 2020-07-07 16:45:03
我将为自定义按钮组件创建结构,如下所示:
...,
props: {
originalArray: {
required: true
}
},
data(){
return {
modifiedArray: this.originalArray.map(x => ({...x}))
}
},
methods: {
yourMethod()
{
//do your logic on the modifiedArray
this.$emit('changed',this.modifiedArray);
}
}然后你可以像这样使用它:
<custom-button :original-array="this.myArray" @changed="newArray => this.myArray = newArray" />发布于 2020-07-07 17:09:18
我会这样做:
const CBtn = {
template: '#c-btn',
props: ['array', 'label'],
data(){
return {
ncTimeout: -1
}
},
computed:{
arr_proxy: {
get(){
// shallow copy to not modify parent array indices
return this.array.slice()
}
}
},
methods: {
update(){
this.notClicked()
if(!this.arr_proxy.includes(this.label))
this.$emit('update:array', this.arr_proxy.concat(this.label))
},
notClicked(){
clearTimeout(this.ncTimeout)
this.ncTimeout = setTimeout(()=>{
let index = this.arr_proxy.findIndex(v => v === this.label)
if(index>=0){
this.arr_proxy.splice(index, 1)
this.$emit('update:array', this.arr_proxy)
}
}, 1000)
}
}
}
new Vue({
components: {
CBtn
},
template: '#main',
data(){
return {arr: []}
}
}).$mount('#app')<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<template id="c-btn">
<button
@click="update"
v-on="$listeners"
v-bind="$attrs"
>
{{label}}
</button>
</template>
<template id="main">
<div>
<c-btn label="1" :array.sync="arr" ></c-btn>
<c-btn label="2" :array.sync="arr" ></c-btn>
<c-btn label="3" :array.sync="arr" ></c-btn>
{{arr}}
<div>
</template>
<div id="app"></div>
因此,是的,您可以使用带有在model选项中定义的value: [propName]和event: [eventName]的v模型,或者带有'update:[propName]'事件的.sync modifier。
https://stackoverflow.com/questions/62770676
复制相似问题