第一步 創建點擊對象頁面元素,並綁定業務數據。
<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。
import ClipboardJS from 'clipboard';
第三步 創建ClipboardJS對象實例。
mounted() { this.clipboard = new ClipboardJS('.copy-button', { text: () => this.copyLink }); ... }
第四步:替換clipboard對象實例的默認的onClick事件。
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 => { }); }; ... }
第五步:監聽並處理操作成功與失敗事件。
mounted() { ... this.clipboard.on('success', this.clipOptions.success); this.clipboard.on('error', this.clipOptions.error); }
其中clipOptions類似如下:
computed: { clipOptions() { return { success: (e) => { this.$message.success('復制成功'); }, error: () => { this.$message.error('復制失敗'); } }; }, ... }
第六步:vue生命周期結束時,銷毀clipboard對象。
unmounted() { this.clipboard && this.clipboard.destroy(); }