[vue/nuxt] Vue Transition 踩小雷 -不要忽略 key

Nick Wu
不想放棄設計的前端工程師
3 min readJan 3, 2020

前陣子在 nuxt 練習專案使用 transition 要做轉場時踩了一個小雷卡了兩三天,就是一個不詳細看文件導致的結果。

先講結果:

当有相同标签名的元素切换时,需要通过 key 特性设置唯一的值来标记以让 Vue 区分它们,【否则 Vue 为了效率只会替换相同标签内部的内容】。即使在技术上没有必要,给在 <transition> 组件中的多个元素设置 key 是一个更好的实践。

When toggling between elements that have the same tag name, you must tell Vue that they are distinct elements by giving them unique key attributes. Otherwise, Vue’s compiler will only replace the content of the element for efficiency. Even when technically unnecessary though, it’s considered good practice to always key multiple items within a <transition> component.

以往在同個頁面內使用 transition 時通常就是會有多個元素要做切換,而多個元素通常也會透過 v-for 搭配 v-if (v-show) 來做渲染,而使用 v-for 我們已經很熟悉地習慣會帶上 key 值,所以在使用 transition 基本上按照官方教學不會有甚麼太大問題。

But, 這次因為要做一個表單填寫步驟,三個步驟(所以自己寫了三個 <div> )然後透過自訂的 step 值來做切換(v-if),且希望有轉場效果。結果就是在做切換時,根本沒有轉場效果!?

<transition name="fade" mode="out-in">
<div v-if="step==0">
...
</div
<div v-if="step==1">
...
</div
<div v-if="step==2">
...
</div
</transition>

結果 google 看了一堆 vue transition not working 的文章就是沒有我要的答案,無意間翻文回官方文件瞄到了這句

...【否则 Vue 为了效率只会替换相同标签内部的内容】

… you must tell Vue that they are distinct elements by giving them unique key attributes….

...
<div v-if="step==0" :key="<don't forget me>">
...
</div
...

到這邊就恍然大悟了,日後請記得要透過賦予key值,告訴 Vue 他們是不同的元素,不然 Vue 就會很好心的幫你節省效能!?…

--

--