1

How to Copy Content to the Clipboard in Vue

 1 year ago
source link: https://masteringjs.io/tutorials/vue/copy-to-clipboard
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

How to Copy Content to the Clipboard in Vue

Oct 19, 2022

To copy text from an input or textarea in Vue, you should write a method to call the element's select() and setSelectionRange() methods using a Vue ref.

Vue.createApp({
  data: () => ({ message: '' }),
  methods: {
    copyText() {
      const element = this.$refs.message;
      element.select();
      element.setSelectionRange(0, 99999);
      document.execCommand('copy');
    }
  },
  template: `
  <div>
    <div>
      <input id="example" v-model="message" ref="message" />
    </div>
    <button @click="copyText()">Click to Copy</button>
    <div>
      <h3>Paste here</h3>
      <div>
        <textarea></textarea>
      </div>
    </div>
  </div>
  `
}).mount('#app');

Below is a live example.

Paste here

Copying non-input fields

To copy text from an element that isn't a textarea or input, you should create a fake textarea using the document.createElement() function. Once you've created a fake textarea, you can set the textarea content to the value you want to copy use the previous approach. Then remove the textarea once the text is copied.

Vue.createApp({
  data: () => ({ message: '' }),
  methods: {
    copyTextNoInput() {
      const storage = document.createElement('textarea');
      storage.value = this.$refs.message.innerHTML;
      this.$refs.reference.appendChild(storage);
      storage.select();
      storage.setSelectionRange(0, 99999);
      document.execCommand('copy');
      this.$refs.reference.removeChild(storage);
    }
  },
  template: `
  <div>
    <div ref="message">This is text that you wish to copy</div>
    <button @click="copyTextNoInput()">Click to Copy</button>
    <div>
      <h3>Paste here</h3>
      <div>
      <textarea></textarea>
      </div>
    </div>
  </div>
  `
}).mount('#app2');
This is text that you wish to copy

Paste here


Vue School has some of our favorite Vue video courses. Their Vue.js Master Class walks you through building a real world application, and does a great job of teaching you how to integrate Vue with Firebase. Check it out!


More Vue Tutorials


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK