# 自定义指令
# 目录结构
|-- src
|-- |-- directive
|-- |-- | |--copy
|-- |-- | | |--index.js
|-- |-- | |--index.js
1
2
3
4
5
2
3
4
5
# 所有指令挂载
- src/directive/index.js
import copy from './copy'
const directive = {
install: function (Vue) {
// 挂载 因为 bind 和 update 方法使用的一个回调函数 所以这里直接将copy函数传入
Vue.directive('copy', copy)
}
}
export default directive
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
- main.js
import Vue from 'vue'
import directive from './directive'
// 挂载自定义指令
Vue.use(directive)
1
2
3
4
2
3
4
# copy
- 用法
<template> <div class='copy-wrapper'> <div class="copy-cen"> <button v-copy="copyData">自定义指令实现 点我复制</button> </div> </div> </template> <script> import { Message } from 'element-ui' export default { data () { return { copyData: 'http://shinewing.com' } }, methods: { onCopy () { let val = this.$refs.url.textContent let input = document.createElement('input') input.value = val console.log(input.value) document.body.appendChild(input) // 获取焦点 input.focus() // 选中指定内容 input.setSelectionRange(0, val.length) if (document.execCommand('copy')) { document.execCommand('copy') Message.success({ message: '复制成功!', showClose: true }) } document.body.removeChild(input) } }, } </script> <style lang='less' scoped> //@import url(); 引入公共css类 .copy-wrapper { margin-top: 50px; height: 100%; display: flex; justify-content: center; align-items: center; .copy-cen { width: 350px; div.url { text-align: center; line-height: 40px; font-size: 14px; font-weight: 600; } button { display: block; // display: inline-block; margin: 20px auto; height: 32px; padding: 0px 12px; line-height: 32px; outline: none; background-color: rgb(113, 88, 255); border: 1px solid rgb(113, 88, 255); cursor: pointer; color: #fff; letter-spacing: 2px; font-weight: 600; border-radius: 4px; transition: all .4s; // text-align: center; } button:hover { background-color: #fff; color: rgb(113, 88, 255); } } } </style>
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80 - 实现 (opens new window)
import { Message } from 'element-ui'
function copy () {
/**
* copy 函数 功能实现
* 利用input可以选择的功能
* 使用document.execCommand("copy") 将 input 选中部分复制到剪切板
*/
let input = document.createElement('input')
input.value = this.value
document.body.appendChild(input)
// 获取焦点
input.focus()
// 选中指定内容
input.setSelectionRange(0, this.value.length)
if (document.execCommand('copy')) {
document.execCommand('copy')
Message.success({
message: '复制成功!',
showClose: true
})
}
document.body.removeChild(input)
}
// 改变 copy 函数内部 this 的指向
const directive = (el, binging) => el.addEventListener('click', copy.bind(binging))
export default directive
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
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