David Martin
David Martin

Reputation: 19

Why can't I get Vue.js to display an image?

I can print the image URL, but I can't get the img tag to display it, though I think I've bound it correctly.

<html>
<head>
  <title>Split VueJS Demo</title>
  <script type="importmap">
    {
      "imports": {
        "vue": "https://unpkg.com/vue@3/dist/vue.esm-browser.js"
      }
    }
  </script>

  <script type="module">
    import { createApp } from 'vue'
    createApp({
      data() {
        return {
          image: 'http://www.cortazar-split.com/dog_origin.jpeg'
        }
      }
    }).mount('#app'); 
  </script>
</head>
<body> 
  <div>
    <div id="app">{{ image }}</div>
    <img id="app" :src="image"/>
  </div>
</body>
</html>

Why doesn't the img tag render the image at the provided URL?

Upvotes: 0

Views: 593

Answers (1)

Kostas Minaidis
Kostas Minaidis

Reputation: 5536

You need to move the img tag inside the div with id="app".

You should never have the same id name used twice in your markup.

The mount method will use the first one found in your markup and ignore any subsequent elements with the same id name.

<html>
<head>
  <title>Split VueJS Demo</title>
  <script type="importmap">
    {
      "imports": {
        "vue": "https://unpkg.com/vue@3/dist/vue.esm-browser.js"
      }
    }
  </script>

  <script type="module">
    import { createApp } from 'vue'

    const data = {
        image: 'http://www.cortazar-split.com/dog_origin.jpeg' 
      }
    console.log(data);
    createApp({
      data() {
        return data;
      }
    }).mount('#app'); 
  </script>

</head>
<body> 
  <div>
    <div id="app">
       {{ image }}
       <img :src="image"/>
    </div>
    <!-- This is outside the scope of the app: -->
    <!-- <img id="app" :src="image"/> -->
  </div>
</body>
</html>

Upvotes: 1

Related Questions