V
V
Vyacheslav2017-10-13 20:12:38
Vue.js
Vyacheslav, 2017-10-13 20:12:38

How to update a variable only in the current vue iteration?

Hello to all!
There is such a simple code for the vue component

<li v-for="(comment, index) in comments" :key="index" class="c">\
  <textarea @click="clickTextarea()" :style="clicked ? active : passive"></textarea>\
</li>\

data: function () {
  return {
    clicked : false,
    active: 'height:auto; ',
    passive: 'height:22px; '
  }
},
methods: {
  clickTextarea: function() {
    this.clicked = true;
  }
}

the meaning is that there is an array of comments, nested, displayed by a tree
, and each comment has its own textarea, which by default has clicked = false, style = passive
when clicking on this textarea, clicked becomes true and, accordingly, the style changes to active
, but the problem is that clicked = true applies to the entire comment level, not just the current iteration,
how can I tell it to do clicked = true only for the current textarea?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2017-10-13
@nskarl

Each comment should have its own clicked, not just one at all.
Add a property to the component - an active comment:

data: () => ({
  ...
  activeComment: null
})

When you click on a textarea, assign the appropriate comment to this property as the value. You assign styles depending on the equality of activeComment and the current comment:
<li v-for="comment in comments">
  <textarea
    @click="activeComment = comment"
    :style="activeComment === comment ? active : passive"
  ></textarea>
</li>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question