Vue自定义指令实现复制功能
import Vue from 'vue' import store from '../store' function copyMethod(value) { let text = '' switch (typeof value) { case 'number': text = value.toString() break case 'object': text = JSON.stringify(value) break default: text = value break } let input = document.createElement('textarea') input.value = text document.body.appendChild(input) input.select() document.execCommand('copy') store.commit('success_msg', '复制成功') document.body.removeChild(input) input = null } Vue.directive('copy', { bind(el, binding) { el.handler = () => copyMethod(binding.value) el.addEventListener('click', el.handler) }, // 更新参数时更新监听函数 componentUpdated(el, binding) { el.removeEventListener('click', el.handler) el.handler = () => copyMethod(binding.value) el.addEventListener('click', el.handler) }, unbind(el) { el.removeEventListener('click', el.handler) el.handler = null }, })
1、main.js中引入自定义指令
import './directives'
2、组件中使用
v-copy="item.name"