a-tooltip气泡指令

/**
 * 气泡指令
 * @param {?String | ?Number} title - 自定义内容
 * @param {?String | 'top'} placement - 气泡冒出位置
 * @param {?String | 'right'} position - 气泡位置
 * @param {Object} binding.value - {title,placement,position}
 * 直接使用: v-tooltip="{title:'我是气泡'}"
 * 配置事件: v-tooltip="{title:'我是气泡',placement: 'top', position:'left'}"
 * 参数说明: title:【自定义内容】; placement【气泡冒出位置】;position【气泡位置】;
 */

export default function (el, binding) {
  if (el.hasIcon) return
  const iconElement = structureIcon(binding.arg, binding.value)
  // 有内容才显示
  if (!iconElement) return
  // 气泡是添加在元素左边还是右边,默认是右边
  binding.value?.position == 'left' ? el.insertBefore(iconElement, el.childNodes[0]) : el.appendChild(iconElement)
  el.hasIcon = true
}



function structureIcon(content, attrs) {
  // 有内容才显示
  if (attrs?.title) {
    // 默认气泡展示的位置
    attrs.placement = attrs.placement ? attrs.placement : 'top'
    // 拼接绑定属性
    let attrStr = ''
    for (let key in attrs) {
      if (attrs[key]) {
        attrStr += `${key}=${attrs[key]} `
      }
    }
    const a = `<a-tooltip ${attrStr}><a-icon type="question-circle" style="margin:0 3px;cursor: pointer;" ></a-icon></a-tooltip>`
    // 创建构造器
    const tooltip = Vue.extend({
      template: a
    })
    // 创建一个 tooltip 实例并返回 dom 节点
    const component = new tooltip().$mount()
    return component.$el
  }
}
//代码里面用到了antd的a-tooltip&a-icon,记得引入

 

posted @ 2023-09-12 18:25  Private!  阅读(215)  评论(0编辑  收藏  举报