vue 不常见操作

 对 v-html 的扩展操作,

 问题产生背景, 在vue 项目中,用v-html渲染 html字符串,这里面包括a 标签等内容,因为某种需求,a 的默认跳转不符合要求,要经过自己定义的方法跳转。

原来的a  : <a href="www.com">eeee</a>

处理后的: <a href="javascript: goTo('www.com')"></a>

正则匹配:

export function handel (str) {
  let imageUrl = str
  var reg1 = /<a.*?href?s*=s*['|"]+?(.*?)['|"]+?/g;
  const re = //files/courses/[a-zA-Z0-9]+/sections/[a-zA-Z0-9]+/content/images/[a-zA-Z0-9]+/g
  if (typeof str === 'string') {
    imageUrl = str.replace(re, function (value) {
      return getDomain() + value
    })
    .replace(reg1, function (url) {
      let newUrl = url.split('href=')[1].replace(/"/g, ''); // 此处最挫,正则没搞好
      // var event = eval()
      return `<a href="javascript:goto('${newUrl}')"`
    })
  }
  return imageUrl
}

 goTo 是一个全局方法:

我是在组件中定义的:

window.goto = function (url) {
  let currentUrl = window.location.href;
  alert(currentUrl)
  if (typeof window['api'] !== 'undefined') {
    var api = window['api']
    api.sendEvent({
      name: 'returnItLab',
      extra: {
        url: currentUrl
      }
    })
  }
  window.location.href = url
}

vue dom:

<div v-html="handel(contentHTML)" >
</div>

  

 

原文地址:https://www.cnblogs.com/adouwt/p/8400138.html