0
    <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?

2
  • 1
    make/call toggle_filter and pass a parameter so you know if you should append to filters or available, no reason to remove an event listener and re-add one Commented Feb 19, 2020 at 16:38
  • If I make <span class="badge badge-pill" @click="toggle('filters', $event)">Label</span> the first time works and the span goes to filters, but when a click again it doesn't go back to available because it still have the @click="toggle('filters', $event)". How do I change the first parameter? Commented Feb 19, 2020 at 16:58

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.