uniapp 電商app 實現複製內容到剪切板
使用Uniapp的話,有現成的api可以直接調用
下面的這個方法只適用於app端,在H5端是不支持的,H5端可以參考下面的PC端的實現方式
export function copyValue(value){
uni.setClipboardData({
data:value,
success: function () {
uni.showToast({
title:"複製成功"
})
},
fail: function () {
uni.showToast({
title:"複製失敗"
})
}
});
}
PC端實現複製內容到剪切板
//此函數的調用就是 @click="copyTitle('內容')"
copyTitle(txt) {
var input = document.createElement("input"); // 創建一個新input標籤
input.setAttribute("readonly", "readonly"); // 設置input標籤只讀屬性
input.setAttribute("value", txt); // 設置input value值爲需要複製的內容
document.body.appendChild(input); // 添加input標籤到頁面
input.select(); // 選中input內容
input.setSelectionRange(0, 9999); // 設置選中input內容範圍
document.execCommand("copy"); // 複製
document.body.removeChild(input); // 刪除新創建的input標籤
//此處的this.$notify是封裝好的一個彈窗組件,你可以直接使用其他的組件,只是提示作用。
this.$notify({
title: '已複製到剪切板'
})
}