vue项目中可能会使用到 v-html=“htmlContent” 来展示富文本内容,对html文本即htmlContent进行安全性过滤:
// html安全性过滤
<template>
<div v-html="safeHtmlContent(htmlContent)"></div
</template>
<script>
import sanitizeHtml from 'sanitize-html';
export default {
data() {
return {
htmlContent: '', // html文本
}
},
methods: {
safeHtmlContent(html) {
const allowedTags = [
'br',
'p',
'span',
'strong'
];
const rule = {
allowedTags,
allowedAttributes: {
'*': ['data-id', 'class', 'style', 'contenteditable'],
}
};
let realHtml = html?.replace(/\n/gm, '<br />');
const safeContent = sanitizeHtml(realHtml, rule);
return safeContent;
}
}
}
</script>
记录于2024-08-17