12

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?

Geert-Jan
  • 18,623
  • 16
  • 75
  • 137
  • 1
    Add a `key` attribute on your `device` elements, with some unique value, like `key="desktop"` and `key="mobile"`. That will tell Vue not to reuse the elements. – Joseph Silber Oct 15 '17 at 18:25
  • @JosephSilber: woeha, that appears to have solved it! If you'd jot that down as an aswer I'm happy to accept. – Geert-Jan Oct 15 '17 at 18:30

1 Answers1

18

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>
Joseph Silber
  • 214,931
  • 59
  • 362
  • 292