LoginSignup
0
0

More than 3 years have passed since last update.

Vueのレンダリング時インクリメントした値がおかしかった件

Posted at

TL;DR

[Vue warn]: You may have an infinite update loop in a component render function.

これが起こる理由としては、レンダリング中に変数の値を変更すると無限ループが発生する。

詳しい解説は下記
You may have an infinite update loop in a component render function. 問題の調査

なにをしようとしたら起こったか

下記のようにcomputedcomputedの検証を行っていた。


<div id="app">
  <p>
    {{incNum}}
    {{incNum}}
    {{incNum}}
  </p>
  <p>
    {{incNumMet()}}
    {{incNumMet()}}
    {{incNumMet()}}
  </p>
  <pre>{{$data}}</pre>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

const app = new Vue({
  el:"#app",
  data:{
    num:0
  },
  computed:{
    incNum:function(){
      return ++this.num;
    }
  },
  methods:{
    incNumMet:function(){
      return ++this.num;
    }
  }
})

・出力結果

405 405 405

406 407 408

{
  "num": 408
}

なんかめちゃくちゃインクリメントされてる・・・

で、下記の様にエラーが出ていた

[Vue warn]: You may have an infinite update loop in a component render function.

(found in <Root>)

原因

描画時にdata内のパラメーターを変更すると無限ループが起こるらしい。
ただ、Vue側が100回で止めてくれるのでブラウザが固まることはない。

詳しい説明は下記

You may have an infinite update loop in a component render function. 問題の調査

解決策

結論としては一度だけ実行するv-onceディレクティブを使用すれば良い

・v-onceを追記


<div id="app" v-once>

・出力結果

1 1 1

2 3 4

{
  "num": 4
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0