Vue NuxtJS 渲染包含 字符串和组件

项目场景:

项目中需要将一段文字去重,将文字传给后台接口后返回了文字中对应的关键字


问题描述

提交到接口的文字 懂得理解, 日子就会很温馨, 日子就会越过越烦恼, 淡看浮华, 懂得宽容, 也会很安宁, 不能理解, 轮回静守
从接口接收到的数据代码:

{
	"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"
      }
 }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值