ホーム > Vue > How to Use VueClipboard Inside v-dialog【Compatible with Vue 3 and Vue 2】
Vue

How to Use VueClipboard Inside v-dialog【Compatible with Vue 3 and Vue 2】

Thank you for your continued support.
This article contains advertisements that help fund our operations.

This article summarizes how to use vue-clipboard to copy text to the clipboard inside the v-dialog of the Vue CSS framework Vuetify.

Vuetify v-dialog

vue-clipboard3

Introduction

Inside v-dialog, the reference to window changes due to its specifications, causing clipboard functionality to not work properly.

Therefore, it is necessary to ensure that the reference to window remains unchanged.

Conclusion

Disable retain-focus

<v-dialog :retain-focus="false"></v-dialog>

Alternatively, change the clipboard reference

Adding one line will make it work.

export default {
  methods: {
    onCopy: function (text) {
      const dialog = document.querySelector(".v-dialog") // ここ
      this.$copyText(text, dialog).then(() => {
        //↑ここ
        console.log("コピー完了後")
      })
    },
  },
}

Full Code

When Using Vue 3

<script setup>
import { ref, onMounted } from "vue"
import useClipboard from "vue-clipboard3"

const { toClipboard } = useClipboard()
const isOpenModal = ref(false)
const text = ref("Text to copy")

function open() {
  isOpenModal.value = true
}

async function copy() {
  try {
    console.log(text)
    await toClipboard(text.value)
    console.log("Copied to clipboard")
  } catch (e) {
    console.error(e)
  }
}
</script>

<template>
  <div>
    <div>
      <v-btn @click="open">Open</v-btn>
    </div>
    <v-dialog :retain-focus="false" v-model="isOpenModal">
      <v-card>
        <div>{{ text }}</div>
        <v-btn @click="copy">Copy</v-btn>
      </v-card>
    </v-dialog>
  </div>
</template>

When Using Vue 2

<template>
  <v-btn small text color="blue" @click="onCopy(text)"> Copy </v-btn>
</template>

<script>
  export default {
    data() {
      return {
        text: "Text to copy",
      }
    },
    methods: {
      onCopy: function (text) {
        // This one line makes it work
        const container = document.querySelector(".v-dialog")
        this.$copyText(text, container).then(() => {
          console.log("Copy complete")
        })
      },
    },
  }
</script>

References

GithubIssue

Summary

I hope this helps someone.

Please Provide Feedback
We would appreciate your feedback on this article. Feel free to leave a comment on any relevant YouTube video or reach out through the contact form. Thank you!