AndyJamesN
AndyJamesN

Reputation: 498

Access Nuxt custom plugin from Composition API

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?

Upvotes: 3

Views: 2145

Answers (2)

Boogie
Boogie

Reputation: 818

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

Upvotes: 1

Steve Bauman
Steve Bauman

Reputation: 8678

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

Upvotes: 2

Related Questions