1

I have an array which i am looping over and outputting the text. I am trying to create an onClick method through which whatever text i click on, it gets pushed to a new array in whatever order they are clicked.

Here is my sample codepen

Here is my code setup:-

<div id="app">
   <v-app>
     <div v-for= "(item,index) in items" :key="item">
       <span class="title" @click="onSelect">{{item.text}}</span>
    </div>
  </v-app>
</div>

and this is the script:-

new Vue({
  el: '#app',
   data() {
      return {
         items: [
             { text: 'foo', value: 'bar' },
             { text: 'bar', value: 'biz' },
             { text: 'buzz', value: 'buzz'}
         ]
      }
    },
 methods: {
   onSelect() {
     let arr = []   
     console.log(arr)   
    }
  }
})

Any help will be appreciated. Thank you.

1 Answer 1

3

You can pass a function as your click handler and pass along the item:

<div id="app">
  <v-app>
    <div v-for="(item, index) in items" :key="item">
      <span class="title" @click="() => onSelect(item)">{{item.text}}</span>
    </div>
  </v-app>
</div>

You can then push that item onto an array:

new Vue({
  el: '#app',
  data() {
    return {
      items: [
        { text: 'foo', value: 'bar' },
        { text: 'bar', value: 'biz' },
        { text: 'buzz', value: 'buzz'}
      ],
      clickedItems: []
    }
  },
  methods: {
    onSelect(item) {
      this.clickedItems.push(item)
      console.log(this.clickedItems)
    }
  }
})

Hope this helps.

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.