3

I am using VueClipboard in my nuxt project.

https://www.npmjs.com/package/vue-clipboard2

I have a plugin file vue-clipboard.js

import Vue from "vue";
import VueClipboard from 'vue-clipboard2';
Vue.use(VueClipboard);

It is imported into nuxt.config

plugins: ['@/plugins/vue-clipboard'],

This sets up a global variable $copyText and in nuxt without the composition API I can do something like

methods: {
  async onCopyCodeToClipboard() {
    const code = 'code'
    await this.$copyText(code)
  },
},

However inside the setup using the composition API (@nuxtjs/composition-api) when I write a function I do not have access to this.$copyText

const onCopyCodeToClipboard = async () => {
  const code = context.slots.default()[0].elm.outerHTML
  // -> Can't use this here - await this.$copyText(code)
}

So how do I make $copyText available to use inside the composition API?

kissu
  • 40,416
  • 14
  • 65
  • 133
AndyJamesN
  • 468
  • 4
  • 14

2 Answers2

2

I was able to get this to work via the Nuxt useContext() method:

import { useContext } from '@nuxtjs/composition-api'

export default function () {
  const { $copyText } = useContext();

  $copyText('code');
}
Steve Bauman
  • 8,165
  • 7
  • 40
  • 56
1

If you are using nuxt bridge, you should directly import the useContext from useNuxtApp() like:

 const { $copyText } = useNuxtApp()

https://nuxt.com/docs/bridge/bridge-composition-api#usecontext-and-withcontext

Boogie
  • 750
  • 7
  • 17