uni-app复制功能

2022-05-19  本文已影响0人  佑安丶

第一种方法

直接用官方给的事件,弊端就是不支持H5

1、在需要的vue页面中调用:
<text class="item-btn" @click="paste(item.spread_url)">复制</text>

2、在methods里调用
paste(value) {
    uni.setClipboardData({
        data: value
    });
}

第二种方法

1、安装 vue-clipboard2 插件:
npm install vue-clipboard2 --save

2、安装完成后在man.js中引入:
import VueClipboard from 'vue-clipboard2'
Vue.use(VueClipboard);

3、在需要的vue页面中调用:
<text class="item-btn"
    v-clipboard:copy="item.spread_url"
    v-clipboard:success="(type) => onCopyResult('success')"
    v-clipboard:error="(type) => onCopyResult('error')">复制
</text>

4、在methods里调用
onCopyResult(type) {
    if (type==='success') {
        this.$msg('复制成功')
    } else {
        this.$msg('复制失败')
    }
}

第三种方法

1、创建个文件
export default function h5Copy(content) {
    if (!document.queryCommandSupported('copy')) {
        // 不支持
        return false
    }
    let textarea = document.createElement("textarea")
    textarea.value = content
    textarea.readOnly = "readOnly"
    document.body.appendChild(textarea)
    textarea.select() // 选择对象
    textarea.setSelectionRange(0, content.length) //核心
    let result = document.execCommand("copy") // 执行浏览器复制命令
    textarea.remove()
    return result
}

2、需要用到的页面引入
import h5Copy from '@/comm/js/junyi-h5-copy.js';

3、需要用到的页面添加点击事件
<view @click="addressCopy">复制地址</view>

4、在methods里调用
addressCopy(){
    let content = this.businessList.address // 复制内容,必须字符串,数字需要转换为字符串
    const result = h5Copy(content)
    if (result === false) {
        uni.showToast({
            title: '不支持',
        })
    } else {
        uni.showToast({
           title: '复制成功',
            icon: 'none'
        })
    }
},

上一篇 下一篇

猜你喜欢

热点阅读