This is the article that you need if you hit the wall while developing your Vue or NUXT web app because you were not able to copy some text to the clipboard with a button or other component.
We will show you how to install and use the clipboard.js variations for NUXT and Vue.js. With this you will be able to move on a bit until the next wall.
The case for Vue-CLI:
With Yarn:
yarn add vue-clipboard2
With NPM:
npm i vue-clipboard2
Add it in your main.js at the src folder:
import Vue from 'vue';
import VueClipboard from 'vue-clipboard2';
import App from 'App.vue';
Vue.use(VueClipboard);
The case for NUXT:
The Nuxt-clipboard2 component make use of vue-clipboard2 to allow your web-app to access the clipboard in a simple way.
You only need two steps. First, include the nuxt-clipboard2 as a dependency in your package manager:
With Yarn:
yarn add nuxt-clipboard2
With NPM:
npm i nuxt-clipboard2
Second: add nuxt-clipboard2 into the modules array of your nuxt.config.js
/* Nuxt.js modules */
modules: [
"nuxt-clipboard2"
],
Usage of nuxt-clipboard2 and vue-clipboard2:
From there you are ready to copy strings to the clipboard using the v-clipboard:copy directive in an element:
<template>
<div>
<p>Now you can copy things to the clipboard!</p>
<button v-clipboard:copy="toCopy">Copy</button>
</div>
</template>
<script>
export default {
data() {
return {
thingToCopy: 'The desired string'
}
}
},
</script>
There is more. You also count with v-clipboard:success, a directive to let the user know if the action was successful and v-clipboard:error for a scenario where would be necessary to use the classic CTRL+C shortcut (quite handy when your users visit your site with legacy browsers).
<template>
<div>
<p>Now you can copy things to the clipboard</p>
<button
v-clipboard:copy="toCopy"
v-clipboard:success="copyFeedback(true)"
v-clipboard:error="copyFeedback(false)"
>
Copy
</button>
<small v-if="copyOk === true">
The text is ready
</small>
<small v-if="copyOk === false">
There was an error. Use Ctrl+C
</small>
</div>
</template>
<script>
export default {
data() {
return {
copyOk: null,
thingToCopy: 'The desired string'
}
}
},
methods:{
copyFeedback(status) {
this.copyOk = status
}
}
</script>
For more info you can visit the nuxt-clipboard2 repo in github or vue-clipboard2 and the origin of everything: clipboard.js, the vanilla JavaScript library from where vue-clipboard2 derived.