在逛帖子的时候经常会看到很多好的代码, 需要复用一下;
当然可以直接选中复制, 但有些时候会直接提供复制的功能, 这是如何实现的呢?
多番查找资料, 发现 vue 中是通过使用 Vue-clipboard2 实现的;
因为网上的资料已经够多了, 就不赘述, 直接引用了:
1, 安装引用
- NPM install --save vue-clipboard2
- import Vue from 'vue'
- import VueClipboard from 'vue-clipboard2'
- Vue.use(VueClipboard)
2,2 中使用方式 (喜欢那种自己挑, 鄙人喜欢 sample2-- 用到了 promise 高大上, 嘿嘿)
- 1,sample1
- <div id="app"></div>
- <template id="t">
- <div class="container">
- <input type="text" v-model="message">
- <button type="button"
- v-clipboard:copy="message"
- v-clipboard:success="onCopy"
- v-clipboard:error="onError">Copy!</button>
- </div>
- </template>
- <script>
- new Vue({
- el: '#app',
- template: '#t',
- data: function () {
- return {
- message: 'Copy These Text'
- }
- },
- methods: {
- onCopy: function (e) {
- alert('You just copied:' + e.text)
- },
- onError: function (e) {
- alert('Failed to copy texts')
- }
- }
- })
- </script>
- 2,sample2
- <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>
3, 打完收工 (差点忘了, IE10 以下不兼容).
来源: http://www.bubuko.com/infodetail-3044775.html