preventing Vue from aggresively reusing dom-elemen

2020-08-17 00:40发布

问题:

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?

回答1:

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.js vuejs2