Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

preventing Vue from aggresively reusing dom-elements

Tags:

vue.js

vuejs2

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?

like image 801
Geert-Jan Avatar asked Oct 15 '17 18:10

Geert-Jan


1 Answers

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>
like image 110
Joseph Silber Avatar answered Jan 01 '23 23:01

Joseph Silber