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.

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');

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!


Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Vue Tutorials