How to get the array value at the moment of clicking with Vue JS

Asked

Viewed 153 times

1

I have been running a simple "for" command with Vue.js. I want to present in "console.log" what was the value clicked.

I arrived at the result of presenting a static array value in console.log, but I need the exact click value.

let app = new Vue({
  el: '#app',
    data: {
      charges:
        [
            { title: 'Título 1' },
            { title: 'Título 2' }
        ]
    },
    methods: {
      modalContent(){
        console.log(this.charges.title = this.charges[0].title);
      }
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
    <div v-for="item in charges">
        <button @click="(modalContent())"> {{ item.title }} </button>
    </div>
</div>

1 answer

0


How you need to get the index of this list (that most of the time is not the best option, the correct is that each line has its own natural identifier), in the v-for also write the in the code you want, pick up the item and also your entry in the list that in the case is (item, index) and also in the method modalContent(index) pass also this index which is the position given in array charges. In his question code if did wrong can not assign that way so I simplified to understand what he is now with the position is bringing the value contained in the list, example:

Vue.config.devtools = false;
Vue.config.productionTip = false;
let app = new Vue({
    el: '#app',
    template: `<div id="app">
    <div v-for="(item, index) in charges">
        <button @click="(modalContent(index))"> {{ item.title }} </button>
    </div>
</div>`,
    data: {
      charges:
        [
            { title: 'Título 1' },
            { title: 'Título 2' }
        ]
    },
    methods: {
      modalContent(index){
        const title = this.charges[index].title;
        console.log(title);
      }
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app"></div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.