Targeting inner html inside Vue.js templates

Viewed 624

I'm new with Vue.js. I want to target a value inside of html element - for example div. That particular element has a values from array of objects and the line is in the shape of <div>{{array.value}}</div>. I also applied a v-for directive, so it looks like this:

<ul v-for="(arr, index) in array"
v-bind:key="index">
<div id="el">{{arr.value}}</div>
</ul>

So, I want to target that {{arr.value}} in the same way I would use document.getElementById("el").value and use that different values (given with v-for) to compare with other equal values (in similar way like it's done in search engines). How to do that in this situation?

1 Answers

Try to use refs instead of id attribute and bind it to the current index then read the text of that ref :

<ul v-for="(arr, index) in array" v-bind:key="index">
    <div :ref="'el'+index">{{arr.value}}</div>
</ul>

these will create refs like el1, el2 ...

somewhere in your script you could do :

 this.$refs.el1[0].innerHTML

or

 this.$refs.el2[0].innerHTML

to get the content of that div element

Vue.config.devtools = false;
Vue.config.productionTip = false;

let app = new Vue({
  el: '#app',

  data() {
    return {
      array: [{
          value: 'bar'
        },
        {
          value: 'foor'
        }, {
          value: 'foobar'
        }
      ]
    }
  },
  methods: {
    log() {
    window.ref2=this.$refs.el2
      console.log(this.$refs.el2[0].innerHTML)
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <ul v-for="(arr, index) in array" v-bind:key="index">
    <div :ref="'el'+index">{{arr.value}}</div>
  </ul>

  <button @click="log">log</button>
</div>

Related