vue+element-ui 項目中實現複製文字連接功能

需求: 點擊複製按鈕,複製一個連接

在GitHub上找到一個clipboard組件,功能比較齊全
使用方法:
 
安裝
npm i clipboard --save

HTML
<template>
  <div class="info_item nomargin">
    <p class="info_content">您的登陸地址</p>
    <p class="info_text link_text">
    <!-- 須要複製的內容,須要指定一個id -->
      <input class="text_link" type="text" id="link" :value="url" ref="link">
      <!-- 複製按鈕 -->
      <button class="btn" @click="copyLink" data-clipboard-action="copy" data-clipboard-target="#link">複製
      </button>
      <!-- 複製成功/失敗的提示 -->
      <span class="message" v-show="isShow">{{word}}</span>
    </p>
  </div>
</template>

 

js文件
// 引入
import Clipboard from 'clipboard'
export default {
  data () {
    return {
      isShow: false,
      word: 'success',
      url: ''
    }
  },

  // 實例建立後,進行默認數據處理
  created () {
    this.url = `${location.hostname}/#/login`
  },
  // 方法集合
  methods: {
    // 複製連接方法
    copyLink () {
      let clipboard = new Clipboard('.btn')
      clipboard.on('success', e => {
        this.isShow = true
        this.word = 'Success'
        setTimeout(() => {
          this.isShow = false
        }, 500)
        clipboard.destroy() // 使用destroy能夠清楚緩存
      })
      clipboard.on('error', e => {
        this.word = 'Fail'
        this.isShow = true
        setTimeout(() => {
          this.isShow = false
        }, 500)
        clipboard.destroy()
      })
    }
  }
}
點擊複製,成功,這樣就複製成功了
這個組件還有一些其餘功能,能夠閱讀下文檔http://www.clipboardjs.cn/
相關文章
相關標籤/搜索