由于document.execCommand即将被弃用,可以使用navigator.clipboard进行替换;
但是navigator.clipboard需要满足条件:必须是https安全链接下才能拿到clipboard对象;
可在vue.config.js下模拟为https连接:
module.exports = defineConfig({
// publicPath : process.env.BASE_URL,
transpileDependencies: true,
devServer: {
// open: true,
// host: 'localhost',
// port: 8080,
https: true,
}
}
同时加上window.isSecureContext判断为true时候为安全状态;
copy(item) { //item为要复制的字符串
if(!navigator.clipboard) {
this.$toast('请更换https连接')
return
}
if (navigator.clipboard && window.isSecureContext) {
navigator.clipboard.writeText(item).then(() => {
this.$toast('复制成功')
}).catch(err => {
this.$toast('复制失败!')
})
}
}