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