第一步 建立點擊對象頁面元素,並綁定業務數據。vue
<el-button type="text" size="mini" class="copy-button" :data-resource-type="scope.data.resource\_type" :data-resource-id="scope.data.resource\_id"> 複製連接 </el-button>
第二步 引入clipboard.js。ios
import ClipboardJS from 'clipboard';
第三步 建立ClipboardJS對象實例。axios
mounted() { this.clipboard = new ClipboardJS('.copy-button', { text: () => this.copyLink }); ... }
第四步:替換clipboard對象實例的默認的onClick事件。post
mounted() { ... const that = this; const oldOnClick = this.clipboard.onClick; this.clipboard.onClick = function onClick(e) { const resource\_type = e.delegateTarget.getAttribute('data-resource-type'); const resource\_id = e.delegateTarget.getAttribute('data-resource-id'); console.log('resource\_type, resource\_id is', resource\_type, resource\_id) that.$axios .post(APIS.Link, { type: 'h5\_ugc\_detail', params: {ugc\_id: resource\_id, ugc\_type: resource\_type}, \_csrf: that.$store.state.csrfToken }) .then(res => { that.copyLink = res.data.data.link; oldOnClick.bind(that.clipboard)(e); }) .catch(err => { }); }; ... }
第五步:監聽並處理操做成功與失敗事件。this
mounted() { ... this.clipboard.on('success', this.clipOptions.success); this.clipboard.on('error', this.clipOptions.error); }
其中clipOptions相似以下:code
computed: { clipOptions() { return { success: (e) => { this.$message.success('複製成功'); }, error: () => { this.$message.error('複製失敗'); } }; }, ... }
第六步:vue生命週期結束時,銷燬clipboard對象。csrf
unmounted() { this.clipboard && this.clipboard.destroy(); }