天天看點

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>
      

  

 

繼續閱讀