Plugins

I. Injetar em instâncias do Vue

Plugin

import Vue from 'vue'

declare module 'vue/types/vue' {
  interface Vue {
    $myInjectedFunction(message: string): void
  }
}

Vue.prototype.$myInjectedFunction = (message: string) => console.log(message)

Uso

<template>
  <div>
    <button @click="$myInjectedFunction()">Clique em mim!</button>
    <button @click="someMethod">Clique em mim!</button>
  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue'

export default defineComponent({
  mounted () {
    this.$myInjectedFunction('funcionando em mounted')
  }
})
</script>

II. Injetar no contexto

Plugin

import { Plugin } from '@nuxt/types'

declare module '@nuxt/types' {
  interface Context {
    $myInjectedFunction(message: string): void
  }
}

const myPlugin: Plugin = (context) => {
  context.$myInjectedFunction = (message: string) => console.log(message)
}

export default myPlugin

Uso

<script lang="ts">
import { defineComponent } from 'vue'

export default defineComponent({
  asyncData (context) {
    context.$myInjectedFunction('funcionando em asyncData')
  }
})
</script>

III. Injeção combinada

Plugin

import { Plugin } from '@nuxt/types'

declare module 'vue/types/vue' {
  interface Vue {
    $myInjectedFunction(message: string): void
  }
}

declare module '@nuxt/types' {
  // nuxtContext.app.$myInjectedFunction dentro de asyncData, fetch, plugins, middleware, nuxtServerInit
  interface NuxtAppOptions {
    $myInjectedFunction(message: string): void
  }
  // nuxtContext.$myInjectedFunction
  interface Context {
    $myInjectedFunction(message: string): void
  }
}

declare module 'vuex/types/index' {
  // this.$myInjectedFunction dentro de stores Vuex
  interface Store<S> {
    $myInjectedFunction(message: string): void
  }
}

const myPlugin: Plugin = (context, inject) => {
  inject('myInjectedFunction', (message: string) => console.log(message))
}

export default myPlugin

Uso

<script lang="ts">
import { defineComponent } from 'vue'

export default defineComponent({
  mounted () {
    this.$myInjectedFunction('funcionando em mounted')
  },
  asyncData (context) {
    context.app.$myInjectedFunction('funcionando em asyncData')
  }
})
</script>