huibing.xie | 1f1606f | 2018-08-20 15:46:55 +0800 | [diff] [blame^] | 1 | // Inspired by https://github.com/Inndy/vue-clipboard2 |
| 2 | const Clipboard = require('clipboard') |
| 3 | if (!Clipboard) { |
| 4 | throw new Error('you shold npm install `clipboard` --save at first ') |
| 5 | } |
| 6 | |
| 7 | export default { |
| 8 | bind(el, binding) { |
| 9 | if (binding.arg === 'success') { |
| 10 | el._v_clipboard_success = binding.value |
| 11 | } else if (binding.arg === 'error') { |
| 12 | el._v_clipboard_error = binding.value |
| 13 | } else { |
| 14 | const clipboard = new Clipboard(el, { |
| 15 | text() { return binding.value }, |
| 16 | action() { return binding.arg === 'cut' ? 'cut' : 'copy' } |
| 17 | }) |
| 18 | clipboard.on('success', e => { |
| 19 | const callback = el._v_clipboard_success |
| 20 | callback && callback(e) // eslint-disable-line |
| 21 | }) |
| 22 | clipboard.on('error', e => { |
| 23 | const callback = el._v_clipboard_error |
| 24 | callback && callback(e) // eslint-disable-line |
| 25 | }) |
| 26 | el._v_clipboard = clipboard |
| 27 | } |
| 28 | }, |
| 29 | update(el, binding) { |
| 30 | if (binding.arg === 'success') { |
| 31 | el._v_clipboard_success = binding.value |
| 32 | } else if (binding.arg === 'error') { |
| 33 | el._v_clipboard_error = binding.value |
| 34 | } else { |
| 35 | el._v_clipboard.text = function() { return binding.value } |
| 36 | el._v_clipboard.action = function() { return binding.arg === 'cut' ? 'cut' : 'copy' } |
| 37 | } |
| 38 | }, |
| 39 | unbind(el, binding) { |
| 40 | if (binding.arg === 'success') { |
| 41 | delete el._v_clipboard_success |
| 42 | } else if (binding.arg === 'error') { |
| 43 | delete el._v_clipboard_error |
| 44 | } else { |
| 45 | el._v_clipboard.destroy() |
| 46 | delete el._v_clipboard |
| 47 | } |
| 48 | } |
| 49 | } |