用require动态引入图片路径怎么做
时间: 2023-07-12 17:18:33 浏览: 55
使用 require 动态引入图片路径可以采用以下方式:
```javascript
const imagePath = require('./images/' + imageName);
```
其中,`./images/` 是图片所在的文件夹路径,`imageName` 是图片的文件名,例如:
```javascript
const imagePath = require('./images/logo.png');
```
注意:使用 `require` 引入图片时,必须保证图片格式是支持的,如 png、jpg、jpeg、gif 等。同时,需要注意的是,`require` 引入图片时,返回的是一个路径字符串,而不是图片本身。如果需要在页面上显示图片,可以使用 `img` 标签,并将其 `src` 属性设置为 `require` 引入的路径字符串。
相关问题
vue require动态路径图片不存怎么使用默认图片
如果动态路径的图片不存在,你可以使用 `require` 加载一个默认图片来代替。具体实现方法如下:
```javascript
<template>
<img :src="imgSrc" alt="">
</template>
<script>
export default {
data() {
return {
imgUrl: 'xxx', // 动态路径
defaultImg: require('@/assets/default.png') // 默认图片路径
}
},
computed: {
imgSrc() {
let img = new Image()
img.src = this.imgUrl
img.onerror = () => {
this.imgUrl = this.defaultImg
}
return this.imgUrl
}
}
}
</script>
```
上面的代码中,我们先在 `data` 中定义了动态路径 `imgUrl` 和默认图片路径 `defaultImg`。在 `computed` 中,我们通过 `img` 对象的 `onerror` 事件来判断动态路径图片是否存在,如果不存在,将 `imgUrl` 赋值为默认图片路径 `defaultImg`。
这样,在模板中只需要绑定 `imgSrc` 就可以了,如果动态路径的图片存在,就会显示动态路径的图片,如果不存在,则会显示默认图片。
vue for循环时 使用require动态路径图片不存在怎么使用默认图片
可以在v-bind中使用三元表达式,判断当前图片是否存在,若不存在则使用默认图片路径。示例代码如下:
```
<template>
<div>
<div v-for="(item, index) in imgList" :key="index">
<img :src="item.imgUrl ? require(`@/assets/${item.imgUrl}`) : require('@/assets/defaultImg.png')" alt="图片">
</div>
</div>
</template>
<script>
export default {
data() {
return {
imgList: [
{ imgUrl: 'img1.png' },
{ imgUrl: 'img2.png' },
{ imgUrl: '' }
]
}
}
}
</script>
```
以上代码中,`imgUrl`为空字符串时,会使用默认图片路径`require('@/assets/defaultImg.png')`。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)