项目场景:
项目中需要将一段文字去重,将文字传给后台接口后返回了文字中对应的关键字
问题描述
提交到接口的文字
懂得理解, 日子就会很温馨, 日子就会越过越烦恼, 淡看浮华, 懂得宽容, 也会很安宁, 不能理解, 轮回静守
从接口接收到的数据代码:
{
"return_code": "200",
"result": {
"Summary": "懂得理解, 日子就会很温馨",
"Keyword": " 懂得 , 理解 , 不能 , 安宁 , 宽容 , 浮华 , 烦恼 "}
}
}
选将字符串部分分割
let keyword = []
if (Keyword !== null) {
keyword = d.Keyword.replace(new RegExp(/( )/g), '').split(',')
}
然后通过原来的文字替换掉,
NPopover
这个是自定义标签,关键: 标签需要全局注册
let content = `懂得理解, 日子就会很温馨, 日子就会越过越烦恼, 淡看浮华, 懂得宽容, 也会很安宁, 不能理解, 轮回静守`
keyword.forEach(v => {
content = content.replaceAll(v, `<NPopover>${v}</NPopover>`)
})
结果(只写两个标签举个例子)
let content = `<NPopover>懂得</NPopover><NPopover>>理解</NPopover>, 日子就会很温馨, 日子就会越过越烦恼, 淡看浮华, 懂得宽容, 也会很安宁, 不能理解, 轮回静守`
这里最开始使用
v-html
渲染无法使用组件的任何功能,<NPopover>文字</NPopover>
成了普通标签,没有任何作用
解决方案:
封装一个
htmlTemplate
组件使用这个组件渲染
export default {
props: {
html: {
type: String,
default: ""
}
},
render(h) {
return h({
template: `<div>${this.html}</div>`
});
}
// Vue jsx中可以使用这种
render(h, context) {
// Worked great in Vue
return h({ template: this.html })
}
render(createElement, context) {
// Kind of works in Nuxt, but doesn't render Vue components at all
return createElement("div", { domProps: { innerHTML: this.html } })
}
};
然后在
nuxt.config.js
文件中添加:
build: {
extend(config, ctx) {
// Include the compiler version of Vue so that wp-content works
config.resolve.alias["vue$"] = "vue/dist/vue.esm.js"
}
}