vue 如何实现复制功能

vue 实现复制功能的两种方法

以下示例,可直接使用参考。

<template>
  <div class="copy">
    <h3>复制功能</h3>
    <input type="text" v-model="msg" />
    <div class="text_div" @click="copyText2">点击我可以复制:{
    
    {
    
     msg }}</div>

    <el-button type="primary" @click="copyText">复制1</el-button>
    <el-button type="primary" @click="copyText2">复制2</el-button>
  </div>
</template>

<script>
export default {
    
    
  name: 'Copy',
  data() {
    
    
    return {
    
    
      msg: '我是需要复制的内容'
    };
  },
  methods: {
    
    
    // 复制:方法一
    copyText() {
    
    
      let inputDom = document.createElement('textarea') // js创建一个文本框
      document.body.appendChild(inputDom) //将文本框暂时创建到实例里面
      inputDom.value = this.msg //将需要复制的内容赋值到创建的文本框中
      inputDom.select() //选中文本框中的内容
      inputDom.focus()
      document.execCommand('copy') //执行复制操作
      document.body.removeChild(inputDom) //最后移出
      this.$message.success('复制成功')
    },
    // 复制:方法二
    copyText2() {
    
    
      navigator.clipboard.writeText(this.msg)
      .then(() => {
    
    
        this.$message.success('复制成功')
      })
      .catch(() => {
    
    
        this.$message.error('复制失败')
      })
    }
  },
};
</script>

<style lang="scss" scoped>
.text_div {
    
    
  cursor: pointer;
}
</style>

猜你喜欢

转载自blog.csdn.net/qq_45565693/article/details/130801706