先上效果图,写一个指令,在dom元素上绑定这个指定,就可以实现tooltip+有复制按钮的功能
在src文件夹里建以下文件
在/directives/index.js里暴露安装插件接口
import Copy from './vcopy/v-copy.js'
export default {
install (Vue) {
Vue.directive('copy', Copy)
}
}
在main.js里引用
import Directive from './directives/index'
Vue.use(Directive)
v-copy.vue
<template>
<div ref="copy-box" class="copy-box">
<el-tooltip ref="tooltip" effect="light" :content="content" placement="top" :disabled="disabled">
<div class="copy-text">{{content}}</div>
</el-tooltip>
<i v-show="!!content" ref="icon-copy" class="el-icon-document-copy" @click="copy(content)"></i>
</div>
</template>
<script>
import {copy} from 'iclipboard';
export default {
data() {
return {
content: '',
disabled: true
}
},
created() {},
mounted() {},
methods: {
copy(val){
copy(val);
}
}
</script>
<style scoped>
.copy-text {
text-overflow: ellipsis;
white-space: nowrap;
}
.el-icon-document-copy {
vertical-align: middle;
cursor: pointer;
}
.copy-box {
display: flex;
justify-content: space-between;
align-items: center;
}
</style>
v-copy.js
import Vue from 'vue'
import Copy from './v-copy.vue'
const CopyIcon = Vue.extend(Copy);
const checkWidthChange = (el) => {
Vue.nextTick(() => {
el.instance.$el.childNodes[0].style.overflow = "initial";
let iconWidth = el.instance.$el.childNodes[1].clientWidth;
let fatherBoxWidth = el.instance.$el.clientWidth - iconWidth;
let childrenWidth = el.instance.$el.childNodes[0].clientWidth;
if (fatherBoxWidth < childrenWidth) {
el.instance.$el.childNodes[0].style.overflow = "hidden";
el.instance.disabled = false
} else {
el.instance.disabled = true
}
})
}
export default {
//第一次绑定到元素时调用
bind: function (el, binding) {
const copy = new CopyIcon({
el: document.createElement('div'),
data() { }
})
//用一个变量接住copy实例
el.instance = copy
el.appendChild(copy.$el);
el.instance.content = binding.value.trim();
//防止有人在行内元素绑定v-copy指令,所以一律转成块级
el.style.display = "block";
//判断需不需要显示tooltip
binding.value && checkWidthChange(el, binding)
},
//组件变动时触发
update: function (el, binding) {
//当宽度有变化时,判断需不需要显示tooltip(因为如果用在表格里,表格是可以拉动列宽)
binding.value && checkWidthChange(el, binding)
},
//指令与元素解绑时调用
unbind: function (el) {
el.instance && el.instance.$destroy()
}
}
引用指令的时候,只需要在元素上加上v-copy
value里写上要显示的文字
<div v-copy="value"></div>