[Vuejs]-How can I getElementByID with dynamic ID values?

3👍

In Vue you don’t need to get the id of each element to set its HTML content, just you need to bind its value as below:

new Vue({
  el: '#app',
  data: {
    dados: [
      { nome: 'D4', value: '' },
      { nome: 'D6', value: '' },
      { nome: 'D8', value: '' },
      { nome: 'D10', value: '' },
      { nome: 'D12', value: '' },
      { nome: 'D20', value: '' },
    ],
  },
  methods: {
    // getting dado by reference to set his value with "valorAleatorio"
    rolagemD20: function(dado) {
      var valorAleatorio = Math.floor(Math.random() * 20 + 1);
      dado.value = valorAleatorio
    },
  },
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.min.js"></script>
<div id="app">
  <div class="col-lg-4" v-for="dado in dados">
  <button class="btn btn-outline-danger" @click="rolagemD20(dado)">
    <p>{{dado.nome}}</p>
    <p>{{ dado.value }}</p>
  </button>
  </div>
</div>

Leave a comment