阻止 Vue 积极地重用 dom 元素
[英] preventing Vue from aggresively reusing dom-elements
本文介绍了阻止 Vue 积极地重用 dom 元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑以下片段:
</模板><模板v-else><div class='device device-tablet-landscape' :class="deviceClass" ><div class="device-scroller-container"><div class='device-scroller'><img id='tryit-img-tablet' :src="srcUrlTablet" v-on:load="onImgLoad" v-on:error="onImgError"/>
</模板>
此代码有条件地呈现两个图像之一.某些用户操作会导致实际显示的图像被切换.
我看到的是:当从 tryit-img-mobile
切换到 tryit-img-tablet
时,图像作为 tryit-img-tablet
的一部分加载code>tryit-img-mobile 将立即以不同的尺寸显示.但是,在图像加载它的新源 :src="srcUrlTablet"
期间,带有 src :src="srcUrlMobile"
的图像仍然显示.
这可能是由于 Vue 对两个模板使用相同的 img-tag.我怎样才能阻止 Vue 这样做,而是使用单独的 img-tags?
解决方案
在这种情况下,Vue 使用特殊的 key
属性告诉它不要重用相同的元素.给每个元素这个属性赋予一个唯一的值,Vue 将不再重用同一个元素:
<div v-if="tryIsMobile"class="设备设备-移动-肖像":class="设备类"键=移动">...<div v-elseclass="设备设备-平板电脑-风景":class="设备类"键=平板电脑">...
Condider the following snippet:
<template v-if="tryIsMobile" >
<div class='device device-mobile-portrait' :class="deviceClass">
<div class="device-scroller-container">
<div class='device-scroller'>
<img id='tryit-img-mobile' :src="srcUrlMobile" v-on:load="onImgLoad" v-on:error="onImgError"/>
</div>
</div>
</div>
</template>
<template v-else>
<div class='device device-tablet-landscape' :class="deviceClass" >
<div class="device-scroller-container">
<div class='device-scroller'>
<img id='tryit-img-tablet' :src="srcUrlTablet" v-on:load="onImgLoad" v-on:error="onImgError"/>
</div>
</div>
</div>
</template>
This code conditionally renders one of the two images. Some user action results in the actual shown image to be toggled.
What I'm seeing is the following: When toggling from say, tryit-img-mobile
to tryit-img-tablet
, the image loaded as part of tryit-img-mobile
will get displayed with different dimensions instantly. However, during the time the image loads it's new source :src="srcUrlTablet"
, the image with src :src="srcUrlMobile"
still displays.
This is probably due to Vue using the same img-tag for both the templates. How can I prevent Vue from doing this, and instead use seperate img-tags?
解决方案
In cases such as this, Vue uses a special key
attribute that tells it not to reuse the same element. Give each element this attribute with a unique value, and Vue will no longer reuse the same element:
<div v-if="tryIsMobile"
class="device device-mobile-portrait"
:class="deviceClass"
key="mobile"
>
...
</div>
<div v-else
class="device device-tablet-landscape"
:class="deviceClass"
key="tablet"
>
...
</div>
这篇关于阻止 Vue 积极地重用 dom 元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文