vue 粘贴复制功能 vue-clipboard2


在逛帖子的时候经常会看到很多好的代码,需要复用一下;

当然可以直接选中复制,但有些时候会直接提供复制的功能,这是如何实现的呢?

多番查找资料,发现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以下不兼容)。

参考原文:https://vue-clipboard2.inndy.tw/

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM