如下图:
这一段html是通过后端返回得到的,我通过innerhtml添加进来的
/** @odoo-module **/
// html_to_text_widget.js
import { registry } from "@web/core/registry";
import { Component } from "@odoo/owl";
import { standardWidgetProps } from "@web/views/widgets/standard_widget_props";
/**
* HtmlToTextWidget
* 将 HTML 内容转换为纯文本显示的组件
*/
class HtmlToTextWidget extends Component {
static template = "wits_html.HtmlToTextWidget";
static props = {
...standardWidgetProps,
};
setup() {
}
get plainText() {
const htmlContent = (this.props.record?.data[this.props.name] || '');
if (!htmlContent) {
return '';
}
try {
// 使用textContent提取纯文本
const tempDiv = document.createElement('div');
tempDiv.innerHTML = htmlContent;
return tempDiv.textContent || '';
} catch (error) {
console.error("Error converting HTML to text:", error);
return '';
}
}
// 生命周期钩子,确保组件正确初始化
connectedCallback() {
super.connectedCallback();
// 初始化时刷新数据
this.invalidate();
}
}
export const htmlToTextWidget = {
component: HtmlToTextWidget,
extractProps: ({ attrs, node }) => ({
}),
};
// 注册到 fields 类别
registry.category("fields").add("html_to_text", htmlToTextWidget);
我现在遇到一个问题:后端返回了一个包含HTML模板的字符串,但前端直接显示的时候,它并没有被渲染成正常的网页内容,而是作为纯文本显示出来。我需要找让这个HTML字符串能够在页面上正常显示,就像普通的HTML一样。
https://cn.vuejs.org/api/built-in-directives.html#v-html