在vue2 中使用 clipboard.js 复制功能

在手机中或web端复制粘贴是一个常用的功能,可以帮助用户方便的复制需要的内容,比如字符串或图片,本文将介绍在vue2中使用clipboard.js复制功能,在vue中使用其实和在普通的js中使用差别并不大,使用起来也是相当的方便。
安装方式
npm install clipboard --save

导入clipboard
import Clipboard from "clipboard"
<template>
  <div id="btn" @click="copy">复制</div>
</template>
<script>
//导入类库
import Clipboard from "clipboard";
export default {
  name: "copy",
  data() {
    return {
      msg: "https://www.bian-jie.cn",
    };
  },
  methods: {
    //复制方法
    copy: function () {
      let that = this;
      let clipboard = new Clipboard("#btn", {
        text: function (trigger) {
          //返回字符串
          return that.msg;
        },
      });
      clipboard.on("success", (e) => {
        //复制成功
        clipboard.destroy();
      });
      clipboard.on("error", (e) => {
        //复制失败
        clipboard.destroy();
      });
    },
  },
};
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
#btn {
  display: inline-block;
  padding: 3px 12px;
  border-radius: 6px;
  background-color: #eee;
  color: #333;
  cursor: pointer;
}
#btn:active {
  background-color: #ddd;
  color: #666;
}
</style>

vue3中的使用案例

<template>
  <div class="itxst">
    <div>
      <input v-model="state.message" />
      <input class="btn" @click="copy" type="button" value="复制" />
    </div>
  </div>
</template>
<script setup>
import { ref, reactive } from "vue";
import Clipboard from "clipboard";

const state = reactive({
  message: "https://www.bian-jie.cn",
});
//复制方法,本例子是vue3环境下,同样在vue2中也可以使用
const copy = () => {
  let clipboard = new Clipboard(".itxst", {
    text: () => {
      //返回需要复制的字符串
      return state.message;
    },
  });
  clipboard.on("success", () => {
    clipboard.destroy();
  });
  clipboard.on("error", () => {
    clipboard.destroy();
  });
};
</script>
<style scoped>
</style>
12 共12条