1

For some reason (dont ask me why), I am having to reset a variable in VueJS via a template. So, In vuejs, I have this:

const someApp = new Vue({
delimiters: ['[[', ']]'],
el: '#some-app',
data: {
    flag: 0,
},
methods: {
    changeFlag(val) {
        if (val === 0){//dumb stuff
            this.flag=0;
        }
        else if (val ===1){
            this.flag=1;
        }
        return this.flag;
    },
    ...

In my template I have this:

        <div :data-flag="changeFlag(0)"></div>
        <p class="card-text"> User story(s):</p>
        <template v-for="item in UserStories">
          <ol v-if="(some_complex_logic_here_via_filters )">
            <li :name="post.id + '__UA'"  :data-flag="changeFlag(1)"> [[ item.something] ]] </li>
          </ol>
      </template>
        <p v-if="(flag === 0)">No user stories found.</p>

The idea is that by excecuting changeFlag(0) and changeFlag(1) I can control the <p> tag later. However, for some reason, the browser seems to hang when I execute this. When I remove the for loop, everything seems OK - the <p> tage with no user stiries renders correctly. The error seems to be when I reset using changeFlag(1).

I am quite new to VueJS and I am wondering if there is some usage error in this...

13
  • Why don't you just change the value of flag without a changeFlag() method. It would seem to be easier... Commented Jan 1, 2020 at 20:21
  • @MarsNebulaSoup: how do I do that without a method? Can you show me some code? Commented Jan 1, 2020 at 20:22
  • someApp.flag = val Commented Jan 1, 2020 at 20:24
  • @MarsNebulaSoup: do I execute this inside some html tag? Commented Jan 1, 2020 at 20:25
  • also, why wouldnt the method approac work? its VERY weird. Commented Jan 1, 2020 at 20:26

1 Answer 1

2

This is indeed an infinite render loop and also bad way to do things in Vue. Do not change reactive data from your template (render function)!!

Read about computed properties

computed: {
  filteredUserStories() {
    return this.UserStories.filter( ...some_complex_logic_here_via_filters... )
  }
}
<div v-if="filteredUserStories.length > 0">  
  <p class="card-text"> User story(s):</p>
  <ol>
    <li v-for="item in filteredUserStories" :key="item.id">{{ item.something }}</li>
  </ol>
</div>
<p v-else>No user stories found.</p>

This is not only much cleaner way to do this in Vue, it's also more effective because filteredUserStories computed property value is cached by Vue and recomputed only when UserStories change or some of the filters change (assuming those filters and their parameters are reactive)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.