在VUE中封装全局方法实现文本复制(copy)

355 阅读1分钟

**定义全局方法、并挂载:**找到main.js,封装function,并且挂载到vue原型上(prototype)

Vue.prototype.copy=function (id) {
    // 创建input框
    var input = document.createElement("input");
    input.value = id;  // 将调用方法穿入进来的值赋给input
    document.body.appendChild(input);  // 将input添加到body中
    input.select(); // 选中文本
    document.execCommand("copy");  // 调用浏览器复制方法、复制成功
    this.$message({  // 利用element弹出成功提示
        type: 'success',
        message: '复制成功'
    });
    input.remove();  // 成功后删除input,防止影响其他元素
}

**在组建中通过this调用方法:**在任一组建中都可使用

<span @click="copy(传入复制的内容)">点我复制</span>