javascriptvue.jsvuetify.js

Vue cannot find the dynamic source of the vuetify v-img element


I need to load an image (from my file system and not url) dynamically with vuetify. However, when I bind a path variable in v-img element, vue cannot find it. When I put it statically using the "required" method, it is ok.

How can I choose a dynamic path with vuetify? Is this a problem with the file loader?

I expect to select the image in run time dynamically. For example, if I have "next" button, I want to load the next image. Here is the code in Vue.js

<html>   
   <v-img 
      v-bind:src="require(myPath)"
      aspect-ratio="1.5"
      max-height="500"
      contain
   />
</html>

<script>    
    data: () => ({
        mycount: 1,
        myPath: "../myimages/2.png"
    })
</script>

[Vue warn]: Error in render: "Error: Cannot find module '../myiamges/2.png'" found in ---> at src/App.vue vue.runtime.esm.js:619 Error: "Cannot find module '../imyimages/2.png'" webpackEmptyContext components sync:2 render Gamesheet.vue:30 VueJS 21 run es6.promise.js:75 notify es6.promise.js:92 flush _microtask.js:18 vue.runtime.esm.js:1888


Solution

  • After a long research and tries I found the answer of my own question.

    The problem here is with the method "require". It needs to know the folder where the images are, during the compilation, when I use a dynamic path. See here. So giving the path including the file name dynamically won't enable the "require" method to identify the folder only. That was imy interpretation.

    So I modifed the code like this and it worked for me:

    <html>   
       <v-img 
          v-bind:src="require('../myimages/' + myFilename)"
          aspect-ratio="1.5"
          max-height="500"
          contain
       />
    </html>
    
    <script>    
        data: () => ({
            mycount: 1,
            myFilename: "2.png"
        })
    </script>
    

    In this case, I could change myFilename in the runtime and it worked as well.