/*
 * @Author: your name
 * @Date: 2021-10-19 10:09:52
 * @LastEditTime: 2021-10-19 16:03:36
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \mall4pc-bbc\plugins\set-DOMPurify.js
 */

import Vue from 'vue'
import util from '~/plugins/util'
import DOMPurify from 'dompurify'
let oldInnerHTML = '' // 记录旧数据

function setHTML (el, binding) {
  let html = binding.value;
  let innerHTML = util.formatHtml(html)
  // 允许的属性 ADD_ATTR:[属性名]
  innerHTML = DOMPurify.sanitize(innerHTML, {ADD_ATTR: ['target']})
  el.innerHTML = innerHTML;
}
Vue.directive("rich", {
  inserted (el, binding) {
    if(binding.value) {
      setHTML(el, binding)
    }
  },
  update: function (el, binding) {
    // 如果旧数据跟新数据一样  直接return
    if (binding.value === oldInnerHTML && !binding.value) {
      return
    }
    oldInnerHTML = binding.value
    if (binding.value) {
      setHTML(el, binding)
    }
  },
});