Vue implements one-click copy function (copy pictures and text)

foreword

  • The function of one-click copy is also frequently used, and it is not that complicated to implement, and it can be realized natively.

  • The principle is to find this Dom element and copy the text and pictures in this element directly.

  • When copying details, there may be a slash (don’t worry if it doesn’t take effect), and the image size will maintain the original image size.

  • Note that copying the style written in scss on the page will not take effect, remember to write the inline style to recognize it

Code

1. Page structure - remember to write inline styles to control the size of the picture

              <div class="QRbutton">
                <el-button type="primary" size="mini" @click="getqrcopy"
                  >复制二维码</el-button>
              </div>
              <div class="QRdetail" ref="QRdom">
                <div class="QRcopy">
                  <img
                    src="需要复制图片地址-http形式"
                    alt="二维码复制"
                    width="180"
                    height="180"
                    style="border: 1px solid #ccc"
                  />
                  <p style="margin: 0px">测试设备-二维码</p>
                </div>
              </div>

2. Page style

.QRbutton {
      display: flex;
      align-content: center;
      margin: 0 0 10px 0;
      .el-button {
        margin-right: 20px;
      }
    }
    .QRdetail {
      .QRcopy {
        width: 200px;
        height: 220px;
        // border: 1px solid #ccc;
        padding: 5px;
        display: flex;
        flex-direction: column;
        align-items: center;
        img {
          width: 180px;
          height: 180px;
        }
      }
    }

3. Page method - find the dom element by ref

// 二维码复制
    getqrcopy() {
      this.$nextTick(function () {
        //nextTick,当前dom渲染完毕的回调
        //打印获取的dom
        console.log('QRdom', this.$refs.QRdom) 
        const selection = window.getSelection()
        const range = document.createRange()
        //传入dom
        range.selectNode(this.$refs.QRdom) 
        selection.addRange(range)
        //copy是复制-中间可能会出现一条杠不用管不影响使用
        document.execCommand('copy') 
        // 清除缓存
        selection.removeAllRanges()
        // 提示用户复制成功
      })
    }

Summarize:

After this process, I believe you have also had a preliminary deep impression on Vue's one-click copy function (copy pictures and text), but the situation we encounter in actual development must be different, so we need to understand it The principle is always the same. Come on, hit the workers!

Please point out any deficiencies, thank you -- Fengguowuhen

Guess you like

Origin blog.csdn.net/weixin_53579656/article/details/131690574