rtician
rtician

Reputation: 15

How do I replace @click event programmatically?

    <div ref="filters"></div>

    <div ref="available">
        <span class="badge badge-pill" @click="add_filter">Label</span>
    </div>
    export default{
        data(){
            ...
        },
        methods:{
            add_filter: function(event){
               this.$refs.filters.appendChild(event.target)
               event.target.removeEventListener('click', this.add_filter)
               event.target.addEventListener('click', this.remove_filter)
            },
            remove_filter: function(event){
               this.$refs.available.appendChild(event.target)
               event.target.removeEventListener('click', this.remove_filter)
               event.target.addEventListener('click', this.add_filter)
            }
        }

So, removeEventListener doesn't work is this case. There's any way that I can accomplish to "toggle" the @click event?

Upvotes: 0

Views: 64

Answers (1)

depperm
depperm

Reputation: 10756

Here is an example with a single method. It checks if a list of the HTMLCollection ([...this.$refs.filters.children]) filters contains the clicked item based on innerText. I added a second element with the same class to show you that it works as long as the text is different.

new Vue({
  el: "#app",
  data() {
    return {}
  },
  methods: {
    toggle_filter: function(event){  
    if([...this.$refs.filters.children].filter(child=>child.innerText==event.target.innerText).length==0){
        this.$refs.filters.appendChild(event.target)
      }else{
        this.$refs.available.appendChild(event.target)
      }
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<h2>Filters</h2>
  <div ref="filters"></div>

<h2>Available</h2>
  <div ref="available">
    <span class="badge badge-pill" @click="toggle_filter">Label 1</span>
    <span class="badge badge-pill" @click="toggle_filter">Label 2</span>
  </div>
</div>

Upvotes: 1

Related Questions