第一种方法(原生)
<Form ref="formInline" :model="formInline" :rules="ruleInline">
<FormItem style="width:560px" class="copyConnect" prop="url" >
<Input v-model="formInline.url" type="textarea" :rows="4"/>
<button @click="toCopy" class="btnConnect" v-show="formInline.url">复制</button>
</FormItem>
</Form>
formInline:{
url: 'https://hjdhfjdklkkdf'
},
ruleInline:{
url: [
{ required: true, message: 'url不能为空', trigger: 'blur' },
{ pattern: /(http|https):\/\/([\w.]+\/?)\S*/, message: 'url格式不正确', trigger: 'blur' }
]
}
// 拷贝
toCopy() {
if(!this.formInline.url){
return this.$Message.info('请输入要复制的内容')
}
const input = document.createElement('input')
document.body.appendChild(input)
input.setAttribute('value',this.formInline.url)
input.select()
if (document.execCommand('copy')) {
document.execCommand('copy')
document.body.removeChild(input)
this.$Message.info('复制成功')
}else{
this.$Message.error('复制失败')
}
},
第二种方法(vue-clipboard2)
npm install --save vue-clipboard2
import VueClipboard from 'vue-clipboard2'
Vue.use(VueClipboard)
<FormItem style="width:560px" class="copyConnect" prop="customerServiceHttp">
<Input v-model="formInline.customerServiceHttp" type="textarea" :rows="4" />
<span v-clipboard:copy="formInline.customerServiceHttp" v-clipboard:success="onCopy" v-clipboard:error="onError" class="btnConnect" v-show="formInline.customerServiceHttp">复制</span>
</FormItem>
onCopy() {
this.$Message.success("复制到剪切板成功!")
},
onError() {
this.$Message.error("复制到剪切板失败!")
},