目录
在项目中 点击按钮 复制 某行文本是很常见的 应用场景,
在 Vue 项目中实现 复制功能 需要借助 vue-clipboard2
插件。
( 出现错误的话,可以试试切换成淘宝镜像源
npm config set registry https://registry.npm.taobao.org )
npm install --save vue-clipboard2
"vue-clipboard2": "^0.3.3",
main.js
文件中全局引入插件示例代码如下:
- import Vue from 'vue'
- import VueClipBoard from 'vue-clipboard2'
-
- Vue.use(VueClipBoard)
-
- new Vue({
- render: h => h(App)
- }).$mount('#app')
在组件中有两种方法可以实现复制功能。
方法一 :
使用 vue-clipboard2
提供的 指令
直接将变量内容复制至剪切板,暂时没有找到处理数据后再复制的方式
- <template>
- <div class="yeluosen">
- <input type="text" v-model="message">
- <el-button
- icon="el-icon-share"
- size="mini"
- style="font-size: 16px;padding: 4px 8px;"
- title="共享"
- v-clipboard:copy="scope.row.url"
- v-clipboard:success="onCopy"
- v-clipboard:error="onError"
- @click="share(scope.row.url)"></el-button>
- </div>
- </template>
复制时,通过 v-clipboard: copy 复制输入的内容 :
- // 复制成功 or 失败(提示信息!!!)
- onCopy: function (e) {
- console.log('复制成功!', e)
- },
- onError: function (e) {
- console.log('复制失败!', e)
- }
方法二:
使用 vue-clipboard2
全局绑定的 $copyText
事件方法
复制动作使用的是 Vue 响应函数方式,这就为复制前控制数据提供了可能!
- // 点击事件
- share(val) {
- this.handleData(val)
- this.$copyText(this.message).then(function (e) {
- alert('Copied')
- }, function (e) {
- alert('Can not copy')
- })
- },
-
- // 数据处理
- handleData(val){
- this.message = this.message + ' ' + val
- }
- <template>
- <div>
- <el-button
- type="success"
- size="small"
- style="margin-left: 10px"
- @click="onCopy"
- >复制</el-button
- >
- </div>
- </template>
-
- <script>
- export default {
- data() {
- return {
- text: "这是一段复制的文本",
- };
- },
- methods: {
- onCopy() {
- this.$copyText(this.pathText).then(
- e=>{
- console.log('复制成功:', e);
- },
- e=>{
- console.log('复制失败:', e);
- }
- )
- }
- }
- };
- </script>
- <template>
- <div>
- <el-input ref="addressInput" v-model="address" :readonly="true">
- <template slot="prepend"> 反馈地址 </template>
- </el-input>
- <el-button @click="copyLink(address)">复制链接</el-button>
- </div>
- </template>
-
- <script>
- export default {
- data() {
- return {
- address: "https://www.baidu.com/", // 地址信息
- };
- },
- methods: {
- // 判断是否是 IE 浏览器
- isIE() {
- if (window.ActiveXObject || "ActiveXObject" in window) {
- return true;
- } else {
- return false;
- }
- },
- // 拷贝地址
- copyLink(url) {
- if (this.isIE()) {
- this.$copyText(url);
- this.$refs.addressInput.select(); // 实现选中效果
- this.$message.success("复制成功!");
- } else {
- this.$copyText(url)
- .then((res) => {
- this.$refs.addressInput.select(); // 实现选中效果
- this.$message.success("复制成功!");
- })
- .catch((err) => {
- this.$message.error("该浏览器不支持自动复制, 请手动复制");
- });
- }
- },
- },
- };
- </script>
-
- <style lang="scss" scoped></style>