首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在按钮上使用v-model?

在按钮上使用v-model?
EN

Stack Overflow用户
提问于 2020-07-07 16:03:34
回答 2查看 612关注 0票数 0

当一个按钮被点击时,我希望将它的name推入一个数组。当按钮没有被点击时,我想从数组中删除它的name

我知道如何使用推送/拼接数组的@click来做到这一点。

我想知道是否有一种简单的方法可以将按钮的点击绑定到数组,就像v-model中的checkbox一样。我知道你不能在button上使用v-model,但如果我们要让button成为它自己的组件,并在上面使用v-model……

<custom-button v-model="myArray"></custom-button>

有没有办法做到这一点呢?

EN

回答 2

Stack Overflow用户

发布于 2020-07-07 16:45:03

我将为自定义按钮组件创建结构,如下所示:

代码语言:javascript
复制
    ...,
    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);
    }

   }

然后你可以像这样使用它:

代码语言:javascript
复制
<custom-button :original-array="this.myArray" @changed="newArray => this.myArray = newArray" />
票数 0
EN

Stack Overflow用户

发布于 2020-07-07 17:09:18

我会这样做:

代码语言:javascript
复制
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')
代码语言:javascript
复制
<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

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62770676

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档