VueJs: v-if 注意事項 keep-aliveを使って List rendering

updated: 2019/10/15

 

v-ifによる条件分岐で大規模なList Renderingはやらないほうがいい。

v-if の component DOM の destroyによるコストが大きくなるから。

infinite scrollを含んだcomponentにv-ifを使った結果、致命的なパフォーマンスissueが発生した。

v-showだと後入れデータの参照エラーが頻発。

一つのcomponentでconditional rendering せずに、別component化してkeep-aliveを使うべきか???

 

.ref

https://vuejs.org/v2/guide/components-dynamic-async.html#keep-alive-with-Dynamic-Components

 

keep-aliveはv-forをcomponentに含む場合、最初の一つしかレンダリングしない

ref: https://vuejs.org/v2/api/#keep-alive

Note, <keep-alive> is designed for the case where it has one direct child component that is being toggled. It does not work if you have v-for inside it. When there are multiple conditional children, as above, <keep-alive> requires that only one child is rendered at a time.

 

しかしvue-routerのrouter-viewをkeep-aliveでwrapすればv-forを含んだcomponentもkeep-aliveできた。

ref: https://router.vuejs.org/api/#router-view

 

<keep-alive>

  <router-view name="hoge"></router-view>

</keep-alive>

**この場合、list renderingを含むcomponent内にnestされた別component、keep-alive + v-ifを含まないものとする。nestされた別componentでなければlist自体にifを使ってもkeep-aliveされる(参照エラー回避のために恐らくifを使う)

例:

computed: {

  targetList() {

    if(this.$route.params === "hoge") {

      return foo

    } else {

      return null

    }

  }

}

 >>> targetListがnullに切り替わってもkeep-aliveされる。ただしtargetListを別Componentにpropsとしてパスするとkeep-aliveが失敗する。

 

related articles:

VueJS: データ取得のタイミングの調整

http://monteecristoo.hatenablog.com/entry/2019/09/27/224418