实现
clipboard.js
const clipboard = {
install(Vue, options) {
Vue.directive('clipboard', {
bind(el, binding, vnode) {
el.$value = binding.value;
el.handler = () => {
let text;
if (typeof binding.value == "function") {
text = binding.value()
} else {
text = el.$value
}
if (text) {
let transfer = document.createElement("input");
document.body.appendChild(transfer);
transfer.value = text; // 这里表示想要复制的内容
transfer.focus();
transfer.select();
document.execCommand("copy", false, null);
transfer.blur();
document.body.removeChild(transfer);
vnode.context.$Message.success("复制成功");
}
}
el.addEventListener('click', el.handler);
},
componentUpdated(el, binding) {
el.$value = binding.value
},
unbind(el) {
el.removeEventListener('click', el.handler)
},
});
}
};
export default clipboard;
main.js
import clipboard from "@/directives/clipboard.js"
Vue.use(clipboard);
知识点
指令钩子函数会被传入以下参数:
el
:指令所绑定的元素,可以用来直接操作 DOM。binding
:一个对象,包含以下 property:name
:指令名,不包括v-
前缀。value
:指令的绑定值,例如:v-my-directive="1 + 1"
中,绑定值为2
。oldValue
:指令绑定的前一个值,仅在update
和componentUpdated
钩子中可用。无论值是否改变都可用。expression
:字符串形式的指令表达式。例如v-my-directive="1 + 1"
中,表达式为"1 + 1"
。arg
:传给指令的参数,可选。例如v-my-directive:foo
中,参数为"foo"
。modifiers
:一个包含修饰符的对象。例如:v-my-directive.foo.bar
中,修饰符对象为{ foo: true, bar: true }
。
vnode
:Vue 编译生成的虚拟节点。移步 VNode API 来了解更多详情。oldVnode
:上一个虚拟节点,仅在update
和componentUpdated
钩子中可用。
binding
value
指令的绑定值,可以是字符串、数字和方法
arg
指令的参数可以是动态的。例如,在 v-mydirective:[argument]="value"
中,argument
参数可以根据组件实例数据进行更新!这使得自定义指令可以在应用中被灵活使用。
vnode
context
是当前的vm实例
fnContext
功能节点的真实上下文