1.创建copy.js,在里面创建指令
import {ElMessage} from "element-plus";
export function clickCopyDirective(app) {
app.directive('copy', {
mounted(el) {
el.onmousemove = ()=>{
el.style.cursor = 'pointer'
}
el.addEventListener('click', () => {
navigator.clipboard.writeText(el.innerHTML).then(()=> {
ElMessage({
message: '复制成功,可贴粘!',
type: 'success',
})
}).catch(()=> {
ElMessage({
message: '复制失败!',
type: 'warning',
})
});
})
}
})
}
2.在main.js中引入该指令
import { createApp } from 'vue'
import App from './App.vue'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import "normalize.css"
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
//在此引入该指令
import { clickCopyDirective } from './utils/copy';
const app = createApp(App)
app.use(ElementPlus, {
locale: zhCn,
})
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
app.component(key, component)
}
//在此调用该指令将实例传过去
clickCopyDirective(app)
app.mount('#app')
3.在需要复制的标签上添加该指令,即可实现复制指令
<span v-copy>要复制的文本</span>
标签:el,vue,app,element,点击,指令,plus,import,文本
From: https://blog.csdn.net/m0_75230853/article/details/140525067