Vue defines src cannot be loaded when using img tag
question
The path is correct, but the image cannot be loaded, as shown in the following example:
<!--vue3Syntax of,vue2similar--> <template> <img :src=""/> </template> <script setup> import {ref} from 'vue'; const src = ref('Picture Path'); </script>
The code and path are fine, but the picture is not displayed
Solution 1: Use require to introduce images (commonJs syntax)
If the project is using vite, the required reference is not supported in vite. The console error: require is not defined
At this time, you need to download the commonJs package
// Download and install commonjs package --vite3yarn add vite-plugin-commonjs // This can be installed in vite2npm i @rollup/plugin-commonjs //2. Add this plugin to the configuration (if it is js, it will be replaced with js version)import commonjs from '@rollup/plugin-commonjs'; const plugins = [ commonjs() as any,// Put it in the first line, otherwise it will not take effect];
Solution 2 (If you use vite, this solution is recommended)
// is the URL of the current module, and the relative path of the image is a complete URLconst list = ref( [{ src: new URL('Relative Path', ).href, }] )
Summary of src attributes of img tags in Vue
When we first come into contact with the vue framework, many friends may encounter the problem that the path does not take effect when using the img tag when setting the dynamic src attribute. Let’s not talk much, let’s start the process!!!
Img tag reference resource pictures
Generally, resources that do not need to be processed by webpack are placed in static, and those that need to be processed are placed in assets
1. Images that do not need to be processed by webpack are placed in static
Images that do not require webpack processing, directly use absolute paths to call the image, such as "/static/xx/"
chestnut
- html code
<img v-bind:src="imgUrl"/>
- js code
data(){ return{ imgUrl:"/static/" } }
It was successfully read. After executing npm run build, check the dist file and found that it was placed in the root directory as it was.
2. Place the pictures that need to be processed by webpack
Can you use import or require to import. import is es6 syntax, and require is commonJS form.
- Chestnut 1
<img class="logo-img" src="@/assets/images/" alt="logo" />
- Chestnut 2
<img :src="require('@/assets/images/')" class="sidebar-logo">
- Chestnut 3
//HTML1 <img class="logo-img" :src="imgUrl" alt="logo" /> //JS data(){ return{ imgUrl:require('./assets/') } }
You can also directly refer to the network path
//HTML1 <img class="logo-img" :src="imgUrl" alt="logo" /> //JS data(){ return{ imgUrl: '/' } }
at last
The above is personal experience. I hope you can give you a reference and I hope you can support me more.