forked from Inndy/vue-clipboard2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
vue-clipboard.js
87 lines (83 loc) · 2.92 KB
/
vue-clipboard.js
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
81
82
83
84
85
86
87
var Clipboard = require('clipboard/dist/clipboard.min.js') // FIXME: workaround for browserify
var VueClipboardConfig = {
autoSetContainer: false,
appendToBody: true // This fixes IE, see #50
}
var VueClipboard = {
install: function (Vue) {
Vue.prototype.$clipboardConfig = VueClipboardConfig
Vue.prototype.$copyText = function (text, container) {
return new Promise(function (resolve, reject) {
var fakeElement = document.createElement('button')
var clipboard = new Clipboard(fakeElement, {
text: function () { return text },
action: function () { return 'copy' },
container: typeof container === 'object' ? container : document.body
})
clipboard.on('success', function (e) {
clipboard.destroy()
resolve(e)
})
clipboard.on('error', function (e) {
clipboard.destroy()
reject(e)
})
if (VueClipboardConfig.appendToBody) document.body.appendChild(fakeElement)
fakeElement.click()
if (VueClipboardConfig.appendToBody) document.body.removeChild(fakeElement)
})
}
Vue.directive('clipboard', {
bind: function (el, binding, vnode) {
if (binding.arg === 'success') {
el._vClipboard_success = binding.value
} else if (binding.arg === 'error') {
el._vClipboard_error = binding.value
} else {
var clipboard = new Clipboard(el, {
text: function () { return binding.value },
action: function () { return binding.arg === 'cut' ? 'cut' : 'copy' },
container: VueClipboardConfig.autoSetContainer ? el : undefined
})
clipboard.on('success', function (e) {
var callback = el._vClipboard_success
callback && callback(e)
})
clipboard.on('error', function (e) {
var callback = el._vClipboard_error
callback && callback(e)
})
el._vClipboard = clipboard
}
},
update: function (el, binding) {
if (binding.arg === 'success') {
el._vClipboard_success = binding.value
} else if (binding.arg === 'error') {
el._vClipboard_error = binding.value
} else {
el._vClipboard.text = function () { return binding.value }
el._vClipboard.action = function () { return binding.arg === 'cut' ? 'cut' : 'copy' }
}
},
unbind: function (el, binding) {
if (binding.arg === 'success') {
delete el._vClipboard_success
} else if (binding.arg === 'error') {
delete el._vClipboard_error
} else {
el._vClipboard.destroy()
delete el._vClipboard
}
}
})
},
config: VueClipboardConfig
}
if (typeof exports === 'object') {
module.exports = VueClipboard
} else if (typeof define === 'function' && define.amd) {
define([], function () {
return VueClipboard
})
}