Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I copy text from Vuetify's v-text-field to clipboard?

I am using Vuetify and trying to copy text from v-text-field component to clipboard when button is clicked. Sample code available on codepen:

<template>
    <div id="app">
      <v-app id="inspire">
        <v-container>
          <v-text-field v-model="text1"></v-text-field>
          <v-btn @click="copyText">copy</v-btn>
        </v-container>
      </v-app>
    </div>
</template>

<script>
    new Vue({
      el: '#app',
      vuetify: new Vuetify(),
      data() { 
        return {
          text1: 'lorem ipsum 123'
        }
      },
      methods: {
        copyText (){
          // copy to clipboard
        }
      }
    })
</script>

The question is what code to put in copyText method of the Vue instance?

like image 941
mlst Avatar asked Aug 29 '19 15:08

mlst


1 Answers

This solution worked for me. It uses the new Clipboard API writeText method which is supported by most modern browsers (see Can I use for more details). Writing to the clipboard does not require special permissions.

  methods: {
    copyText() {
      navigator.clipboard.writeText(this.text1);
    }
  }
like image 85
Coola Avatar answered Feb 10 '23 05:02

Coola