vue替换富文本里面的<img>标签
时间: 2024-09-29 13:11:24 浏览: 84
Vue.js 中替换富文本中的 `<img>` 标签通常涉及到将HTML内容插入到模板中,并且需要处理动态加载图片的情况。你可以使用 Vue 的 `v-html` 或者 `DOM` API 来实现这个功能。以下是简单的步骤:
1. **使用 v-html**:
当你需要保留HTML结构时,可以使用 `v-html` 指令来安全地插入包含 `<img>` 标签的内容。确保设置 `security` 属性为 `false`,因为默认情况下它会自动转义 HTML 内容。
```html
<div v-html="richText" :的安全="false"></div>
```
2. **处理 img 标签**:
对于 `<img>` 标签,可以在渲染之前遍历并转换成 Vue 能识别的格式,如使用 `src` 和 `alt` 属性:
```javascript
computed: {
safeRichText() {
return this.richText.replace(/<img(.*?)\/?>/g, (match) => {
let attrStr = match.match(/[^\s]+/g).join(' ');
return '<img ' + attrStr + ' />';
});
}
}
```
3. **懒加载图片**:
如果你想在图片实际加载前隐藏它们,可以使用 Vue 的 `v-if` 和事件监听器(例如 `load`)来控制:
```html
<img :src="imageUrl" :alt="altText" v-if="!imageUrlLoaded" @load="onImageLoad" />
```
```javascript
methods: {
onImageLoad() {
this.imageUrlLoaded = true;
}
},
data() {
return {
imageUrl: '',
imageUrlLoaded: false,
altText: ''
};
}
```
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.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)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)