GrumpyCoder
GrumpyCoder

Reputation: 63

I get error in console when use "v-if" directive. Infinite loop

After when I use v-if, I get a [Vue warn] in my console, no idea how to solve this problem. [Vue warn]: You may have an infinite update loop in a component render function.

<template>
  <div class="example-component">
      <div class="spinner-box" v-if="loadComplete = !loadComplete">
        <div class="spinner-inner">
          <i class="fas fa-circle-notch fa-spin"></i>
        </div>
      </div>
  </div>
</template>

<script>
export default {
  name: 'ExampleComponent',
  data () {
    return {
      loadComplete: false
    }
  }
</script>

Upvotes: 3

Views: 548

Answers (2)

daniloisr
daniloisr

Reputation: 1367

Just to clarify where the infinite update loop came.

The v-if="loadComplete = !loadComplete" is an assignment, where you are assigning the value !loadComplete to loadComplete. Whenever you assign a variable in Vue it will trigger a new render, and on the next render it is executing the same assignment again... and this result in an infinite loop.

@PaulTsai gave a great example using the correct way v-if="!loadComplete"

Upvotes: 3

Paul Tsai
Paul Tsai

Reputation: 1009

Change

v-if="loadComplete = !loadComplete"

To

v-if="!loadComplete"

Example

https://2ozkjp4vyp.codesandbox.io/

Edit Vue Template

<template>
    <div id="app">
        <img width=200 src="./assets/logo.png">
        <div class="loader" v-if="!loadComplete"></div>
        <div v-else>
            <p>asynchronous data from firebase</p>
            <button @click="loadDataFromFirebase">Reload</button>
        </div>
    </div>
</template>

<script>
    export default {
    name: 'app',
        data: () => ({
            loadComplete: false
        }),
        mounted () {
            this.loadDataFromFirebase()
        },
        methods: {
            loadDataFromFirebase () {
                this.loadComplete = false
                setTimeout(() => {
                    this.loadComplete = true
                }, 1000)
            }
        }
  }
</script>

Upvotes: 3

Related Questions