Home > database >  How to change style of element in click if its in a for loop in Javascript Vue?
How to change style of element in click if its in a for loop in Javascript Vue?

Time:09-11

If I have an element like this that is in a for loop:

<p  id="description" @click="onClickDescription">{{ review.text }}</p>

meaning that there is more than one of these elements, how can I change the style of the element that was clicked.

I have this function:

onClickDescription(e) {
  console.log(e)
  let d = document.getElementById('description');
  d.style.webkitLineClamp = 99;
}

But this will change the style of all my <p> elements instead of just the one I clicked. How can I get around this?

CodePudding user response:

You can use index or id if you have it in review object:

new Vue({
  el: '#demo',
  data() {
    return {
      reviews: [{text: 'aaa'}, {text: 'bb'}, {text: 'ccc'}],
      selected: null
    }
  },
  methods: {
    onClickDescription(i) {
      this.selected = i
    }
  }
})
.description {
  color: green;
}
.active {
  color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  <div v-for="(review, i) in reviews" :key="i">
    <p  : @click="onClickDescription(i)">{{ review.text }}</p>
  </div>
</div>

  • Related