The src attribute of img in Vue is bound to the static folder instance, vuesrc
Many people encounter this problem during vue development: the src attribute of img is bound to the url variable, but the image loading fails.
In most cases, developers use incorrect writing methods, such:
This is definitely not correct. The correct method should be v-bind:
However, even if you use the correct syntax, the image cannot be displayed because your imgUrl uses the path of the local image.
For example, the following file structure is available:
Now, we want to use the logo.png image in the src/assets/directory in App. vue. Therefore, we set:
imgUrl = './assets/logo.png'
The strange thing is that the image loading fails. View the source code of the webpage and find an error:
Looking at this error code, we found that the webpage regards the root domain name as the root directory of the relative path. However, the path of our file is relative to the root directory of the project file, and of course we cannot find it.
In this case, go to the dist folder after build. The structure of the file is as follows:
Do you only need to change the url to./static/img/logo.png? Still cannot. Open the img folder and we can find that all the file names are added with a random string, and the original file name cannot match.
So how should I load local images? Looking back at the vue-cli's file structure, find that one of them is named staticfolder. Try to put logo.png in this folder, and then modify imgUrl:
imgUrl = '/static/logo.png'
After successfully reading the logo.png file, execute npm run buildand then upload the distfile, and find that logo.png is stored in the root directory intact.
Originally, there was a problem with the previous directory structure. static files such as images should be placed in this static folder, the files in this folder (folder) it is stored in the root directory of the website according to the original structure. Then we can use the/static absolute path to access these static files.
In addition, if you want to read the local image without adjusting the directory structure, another method is to directly input the image encoding. That is:
imgUrl = require('./assets/logo.png')
In this way, you can read the images under the project path, but note that because CommonJS only allows the use of string literal, the flexibility of this method is still poor, we recommend that you put static files in the static folder.
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.