vue自定义指令 copy
在vue 的项目里,可以通过点击按钮直接复制想要的内容。
新建一个项目 按照以下方式把对应的文件改造下就可以了 (cv即食)
使用自定义指令 v-copy 其实就是把我们想要复制的内容赋值给cotpyTexts 这个变量,点击复制按钮的时候就把需要复制的内容复制过来了。
第一步,src/directives下面新建两个文件directives.js 和 v-copy.js
v-copy.js文件代码:
import { Message } from 'element-ui'
const vCopy = {
/**
* bind 钩子函数,第一次绑定时调用,可以在这里做初始化设置
* el: 作用的 dom 对象
* value: 传给指令的值,要 copy 的值
*/
bind(el) {
el.handel = () => {
if (!el.$value) {
Message({
message: '无复制内容',
type: 'warning'
})
return
}
const textarea = document.createElement('textarea')
textarea.readOnly = 'readonly'
textarea.style.position = 'absolute'
textarea.style.left = '-99999x'
textarea.value = el.$value
document.body.appendChild(textarea)
textarea.select()
textarea.setSelectionRange(0, textarea.value.length)
const result = document.execCommand('Copy')
if (result) {
Message({
message: '复制成功',
type: 'success'
})
}
document.body.removeChild(textarea)
}
el.addEventListener('click', el.handel)
},
componentUpdated(el, { value }) {
el.$value = value
},
// 指令与元素解绑的时候,移除事件绑定
unbind(el) {
el.removeEventListener('click', el.handel)
}
}
export default vCopy
directives.js 文件:
import copy from './v-copy'
// 自定义指令
const directives = {
copy
}
// 批量注册指令
export default {
install(Vue) {
Object.keys(directives).forEach(key => {
Vue.directive(key, directives[key])
})
}
}
直接在vue页面中v-copy使用即可: role.vue
<template>
<div>
<el-button v-copy="copyValue" round class="copy-btn">复制</el-button>
<el-button round class="copy-btn clear-btn" @click="clear">清空 </el-button>
</div>
</template>
<script>
export default {
data() {
return {
copyValue: ''
}
},
created() {
this.convertResFile()
},
methods: {
async convertResFile() {
try {
const res = await getVexConvertRes()
if (res.code === 200) {
this.copyValue = res.data
}
} catch (error) {
this.$message.error(error)
this.copyValue = ''
}
},
clear() {
this.copyValue = ''
}
}
}
</script>