cnpm install clipboard --save-dev
import clipboard from 'clipboard';
Vue.prototype.clipboard = clipboard;
<el-button @click="copy(categoryCode)" id="getCategoryCode">複製</el-button>
copy (data) {
let clipboard = new this.clipboard('#getCategoryCode', {
text: function () {
return data
}
})
clipboard.on('success', e => {
this.$message({message: '複製成功', showClose: true, type: 'success'})
clipboard.destroy()
})
clipboard.on('error', e => {
this.$message({message: '複製失敗,', showClose: true, type: 'error'})
clipboard.destroy()
})
},
上面是直接實用的方式
下面是我寫的指令方式複製
cnpm install clipboard --save-dev // 安裝依賴
import clipboard from 'clipboard'; // main.js 引入
Vue.directive('copy', { // 自定義指令copy
bind(el, bingind, vnode) {
let copy = new clipboard(el, {
text: function () {
return JSON.stringify(bingind.value)
}
});
copy.on('success', e => {
alerts('複製成功', 'success') // 自己寫的彈框
})
copy.on('error', e => {
alerts('複製失敗,', 'error') // 自己寫的彈框
})
}
});
<el-button v-copy="params">複製</el-button> // 頁面中使用 params是要複製的內容
或者
import clipboard from 'clipboard';
Vue.directive('copy', {
bind(el, bingind, vnode) {
const copy = new clipboard(el);
el.dataset.clipboardText = JSON.stringify(bingind.value)
copy.on('success', e => {
alerts('複製成功', 'success') // 自己寫的彈框
});
copy.on('error', e => {
alerts('複製失敗,', 'error') // 自己寫的彈框
});
},
update(el, bingind) {
el.dataset.clipboardText = JSON.stringify(bingind.value)
}
});