Skip to content

Commit

Permalink
Add method: this.$copyText
Browse files Browse the repository at this point in the history
  • Loading branch information
Inndy committed Nov 8, 2017
1 parent 110c4c8 commit 8ad94e8
Show file tree
Hide file tree
Showing 3 changed files with 72 additions and 0 deletions.
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,17 @@ new Vue({
</script>
```

## I want to copy texts without a specific button!

Yes, you can do it by using our new method: `this.$copyText`. see [sample2](sample2.html).

Modern browser have some limiation like that you can't use `window.open` without a user iteraction.
So there's a same restriction on copy things! Test it before you use it. Make sure you are not
using this method inside any async method.

Use it before reading [this issue](https://github.com/zenorocha/clipboard.js/issues/218) and
[this page](https://github.com/zenorocha/clipboard.js/wiki/Known-Limitations).

### Contribution

PRs welcome, and issues aswell! If you want any feature that we don't have currently, please create a issue for feature request.
Expand Down
42 changes: 42 additions & 0 deletions sample2.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>vue-clipboard2 sample app</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.6/vue.js"></script>
<script src="dist/vue-clipboard.js"></script>
</head>
<body>
<div id="app"></div>

<template id="t">
<div class="container">
<input type="text" v-model="message">
<button type="button" @click="doCopy">Copy!</button>
</div>
</template>

<script>
new Vue({
el: '#app',
template: '#t',
data: function () {
return {
message: 'Copy These Text'
}
},
methods: {
doCopy: function () {
this.$copyText(this.message).then(function (e) {
alert('Copied')
console.log(e)
}, function (e) {
alert('Can not copy')
console.log(e)
})
}
}
})
</script>
</body>
</html>
19 changes: 19 additions & 0 deletions vue-clipboard.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,25 @@ var Clipboard = require('clipboard')

var VueClipboard = {
install: function (Vue) {
Vue.prototype.$copyText = function (text) {
return new Promise(function (resolve, reject) {
var fake_el = document.createElement('button');
var clipboard = new Clipboard(fake_el, {
text: function () { return text },
action: function () { return 'copy' }
});
clipboard.on('success', function (e) {
clipboard.destroy();
resolve(e);
});
clipboard.on('error', function (e) {
clipboard.destroy();
reject(e);
});
fake_el.click();
});
};

Vue.directive('clipboard', {
bind: function (el, binding, vnode) {
if(binding.arg === 'success') {
Expand Down

0 comments on commit 8ad94e8

Please sign in to comment.