需求: 點擊復制按鈕,復制一個鏈接
在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/
