今天遇到了一个需求,需要实现点击按钮复制内容,然后粘贴到其他地方。
效果如图:
以下为解决问题的过程:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vue实现复制功能演示</title>
</head>
<body>
<div id="dowebok">
<h1 style="margin-bottom: 200px;">Vue实现复制功能演示</h1>
<div>
<input v-model="text" placeholder="请输入要复制的内容">
<button @click="toCopy">复制</button>
</div>
</div>
<script src="js/vue.min.js"></script>
<script src="js/script.js"></script>
</body>
</html>
var app = new Vue({
el: '#dowebok',
data: {
text: '',
},
methods: {
toCopy: function () {
if (!this.text) {
alert('请输入要复制的内容')
} else {
var copyInput = document.createElement('input')
copyInput.setAttribute('value', this.text)
document.body.appendChild(copyInput)
copyInput.select()
try {
var copyed = document.execCommand('copy')
if (copyed) {
document.body.removeChild(copyInput)
alert('复制成功')
}
} catch {
alert('复制失败,请检查浏览器兼容')
}
}
}
}
})