gileneusz
gileneusz

Reputation: 1485

ineffective computed loop in vuejs

I've got array as below:

return {
   items: [
      { active: false, text: 'text1', textOutput: ''},
      { active: false, text: 'text1', textOutput: ''},
      { active: false, text: 'text1', textOutput: ''},
      ...
   ],
}

now, the purpose of this array is to output data to the DOM, using computed property as below.

I want to output only the data where active: true, which is changing onclick in other part of the web, so computed resultDOM is watching for this change and changing only items.active="true". Also I use text-fields to change items.text[i] values.

computed: {
 resultDOM () {
        for (var i=0; i<this.items.length; i++) {
          if (this.items[i].active) {
            this.items[i].textOutput = '<li>' + this.items[i].text + '</li>'
            console.log('bam')
          }
          else {
            this.items[i].textOutput = ''
            console.log('bam else')
          }          
        }
        var output=''
        for (var i=0; i<this.items.length; i++) {
          output = output + this.items[i].textOutput
        }
        return output
 }
}

The problem is that this takes some time to execute and every time I change only one active to true (or items.text value) computed is doing check on every element of the table, so it's very ineffective. Can I ask you for tips, how should I improve my code to be more efficient? What is the right way to do it?

edit:

<div  v-html="resultDOM"></div>

Upvotes: 0

Views: 985

Answers (1)

oniondomes
oniondomes

Reputation: 2063

You can avoid using computed at all if you take advantage of conditional rendering and v-for directive:

const app = new Vue({
  el: "#app",
  data: {
    items: [
      { active: true, text: 'text1',},
      { active: true, text: 'text2',},
      { active: false, text: 'text3',},
    ],
  },
})
<script src="https://unpkg.com/vue"></script>

<div id="app">
  <ul>
    <li v-for="item in items" v-if="item.active" v-text="item.text"></li>
  </ul>
</div>

jsfiddle

Upvotes: 2

Related Questions