1. 实现效果
2. vue3 注册全局自定义指令详解(v-copy)
- 在src中,新建
directive
文件夹,在次新建 clipboard
文件夹(copy指令),创建 index.js
书写 copy指令方法
directive/clipboard/index.js
clipboard(copy指令)完整代码
import Clipboard from 'clipboard'
if ( !Clipboard ) {
throw new Error( '你须先运行 npm install `clipboard` --save ' )
}
export default {
beforeMount( el, binding ) {
if ( binding.arg === 'success' ) {
el._v_clipboard_success = binding.value
} else if ( binding.arg === 'error' ) {
el._v_clipboard_error = binding.value
} else {
const clipboard = new Clipboard( el, {
text() {
return binding.value
},
action() {
return binding.arg === 'cut' ? 'cut' : 'copy'
}
} )
clipboard.on( 'success', e => {
const callback = el._v_clipboard_success
callback && callback( e )
} )
clipboard.on( 'error', e => {
const callback = el._v_clipboard_error
callback && callback( e )
} )
el._v_clipboard = clipboard
}
},
beforeUpdate( el, binding ) {
if ( binding.arg === 'success' ) {
el._v_clipboard_success = binding.value
} else if ( binding.arg === 'error' ) {
el._v_clipboard_error = binding.value
} else {
el._v_clipboard.text = function() {
return binding.value
}
el._v_clipboard.action = function() {
return binding.arg === 'cut' ? 'cut' : 'copy'
}
}
},
unmounted( el, binding ) {
if ( binding.arg === 'success' ) {
delete el._v_clipboard_success
} else if ( binding.arg === 'error' ) {
delete el._v_clipboard_error
} else {
el._v_clipboard.destroy()
delete el._v_clipboard
}
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 在
directive
文件夹中新建 index.js
,编写整合所有的自定义指令
import clipboard from './clipboard'
const directives = {
clipboard
}
const registerDirective = app => {
Object.keys( directives ).forEach( key => {
app.directive( key, directives[key] )
} )
}
export default registerDirective
3. main.js
注册全局自定义指令,挂载到 vue 上
import { createApp } from "vue";
import registerDirective from "@/directive";
const app = createApp(App);
const initApp = async () => {
registerDirective(app);
app.mount("#app");
};
initApp();
4. 页面使用
<template>
<el-row :gutter="10">
<el-col :span="18">
<el-input placeholder="请输入" v-model="value" />
el-col>
<el-col :span="6">
<el-button
type="primary"
v-clipboard:copy="value"
v-clipboard:success="clipboardSuccess"
v-clipboard:error="clipboardError"
>
复制
el-button>
el-col>
el-row>
template>
<script setup>
const value = ref('')
const clipboardSuccess = () => {
ElMessage.success( '复制成功' )
}
const clipboardError = () => {
ElMessage.error( '复制失败' )
}
script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28