Vuejs: How to access data from a v-for within a method?

Asked

Viewed 309 times

1

I have the following problem, I need to manipulate some variables that are in my date, through a click, which is within a list (v-for). But I can only create the condition directly inside the click, I cannot make the comparisons through a method.

Follow an example:

js

var app = new Vue({
  el: '#app',
  data: {
    exemplo1: false,
    exemplo2: false,
    carros: [
      {
      "tipo": "Passeio",
      "cor": "Azul",
      "detalhe": "Sim"
      },
      {
      "tipo": "4x4",
      "cor": "Preto",
      "detalhe": "Não"
      }
    ]
  },
  methods: {
    verificaDetalhe: function(){
        console.log(this.carros.detalhe);
    },
  },
})

html

<div id="app">
  <div v-for="carro in carros">
    <h1>Tipo: {{carro.tipo}}</h1>
    <h2>Cor: {{carro.cor}}</h2>
    <a href="#" v-on:click="verificaDetalhe()">Detalhe</a>
    <a href="#" v-on:click="if(carro.detalhe == 'Sim'){ exemplo1 = true}">Detalhe2</a>
  </div>
  <div v-if="exemplo1">Exemplo1</div>
  <div v-if="exemplo2">Exemplo2</div>
</div>

By clicking on to "Details2" of the first car on the list, the condition is satisfied, but as I have several rules, I wanted to use a method for this.

How can I check the list through a method? I tried to use a foreach but failed.

Follow a codepen link to help you see what I’m trying to: https://codepen.io/haykou/pen/eGzdLL

1 answer

3


You need to pass the car:

<a href="#" v-on:click="verificaDetalhe(carro)">Detalhe</a>

And get on the other end:

methods: {
  verificaDetalhe: function(carro){
    console.log(carro.detalhe);
  },
},

Browser other questions tagged

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