shak imran
shak imran

Reputation: 332

How to use own JS as a plugin using Nuxt.js

I am using nuxt.js. I have a helper.js script inside plugins folder which has a simple Test() function. Now how can I can call the Test() method inside pages which is in helper.js file.

helper.js file:

export default function Test() {
   return 'This is test'
}

Upvotes: 12

Views: 29590

Answers (6)

Farzad.Kamali
Farzad.Kamali

Reputation: 593

myPlugin.js

export default (_, inject) => {
    const myFuncA = value => return value;
    const myFuncB = value => return myFuncA(1) + value;
    inject('myPlugin', { myFuncA, myFuncB }
)

nuxt.config.js

plugins[
'@/plugin/myPlugin.js'
]

myComponent.vue

created(){
   console.log( this.$myPlugin.funcA(2) );
}

in myPlugin.js, instead of "_" can use some public nuxt variables like {$config}

Upvotes: 1

SanBen
SanBen

Reputation: 2798

Using the inject method

There is actually an easy way to do this by using the 'inject' method. As described in the docs...

The plugins directory contains JavaScript plugins that you want to run before instantiating the root Vue.js Application. This is the place to add Vue plugins and to inject functions or constants. Every time you need to use Vue.use(), you should create a file in plugins/ and add its path to plugins in nuxt.config.js.

in your plugin simply use inject like this:

export default ({ app }, inject) => {
  inject('myInjectedFunction', (string) => console.log('That was easy!', string))
}

and in your components you can use it as follows:

export default {
  mounted(){
    this.$myInjectedFunction('works in mounted')
  },
  asyncData(context){
    context.app.$myInjectedFunction('works with context')
  }
}

"Manual" injection

If you plan on injecting something yourself check out the Vue Docs on Adding Instance properties

There may be data/utilities you’d like to use in many components, but you don’t want to pollute the global scope. In these cases, you can make them available to each Vue instance by defining them on the prototype

Vue.prototype.$appName = 'My App'

And prefix these injected properties with '$'...

$ is a convention Vue uses for properties that are available to all instances. This avoids conflicts with any defined data, computed properties, or methods.

Upvotes: 10

Sudam Dissanayake
Sudam Dissanayake

Reputation: 146

Below is a a custom js plugin that I have used in one of my nuxt projects.

  1. create your file inside the plugins folder, and make your own function as below
export default (context, inject) => {
  const formatDate = (dateTime) => {
    if (typeof(dateTime) === 'undefined' || dateTime === null) {
      return null;
    }
    let tempDate = new Date(dateTime);
    tempDate.setMinutes(tempDate.getMinutes() -
      tempDate.getTimezoneOffset());
    tempDate = tempDate.toISOString().slice(0, 16);
    return tempDate;
  }
  // Inject $hello(msg) in Vue, context and store.
  inject('formatDate', formatDate)
  // For Nuxt <= 2.12, also add 👇
  context.$formatDate = formatDate
}
  1. Add the plugin to nuxt.config.js and you will be able to use it globally.

Upvotes: 0

mblancodev
mblancodev

Reputation: 506

Hello you can inject the function globally into Vue doing the following:

./plugins/myPluging.js

import Vue from 'vue'

Vue.prototype.$nameOfMyPlugin = (args) => {
 // Code here
}

Them in all your components you can access it this way:

./components/myComponent.vue

<script>
export default {
  name: 'c',
  mounted () {
   this.$nameOfMyPlugin('something useful')
 }
}

</script>

And that's it :) hope this helps.

-- Reference: https://nuxtjs.org/guide/plugins/#inject-in-root-amp-context

Upvotes: 3

Ali Gilan
Ali Gilan

Reputation: 365

to access your global methods entire application:


1-create ./plugins/helpers.js .


2-edit ./plugins/helpers.js :

import Vue from 'vue'
Vue.mixin({
    methods:{
        mySpecialMethod(value){
            console.log(value)
        },
    }
})

3-edit ./nuxt.config.js :

plugins: [
    ...
    { src: '~/plugins/helpers' },
    ...
],

now you can access your global method by:

this.mySpecialMethod()

Upvotes: 23

dahrens
dahrens

Reputation: 3959

If you just want to use the code in your components (pages), you only need to import and use the method:

TestPage.vue

<template>
  <div>
    <h1>{{ getTest }}</h1>
  </div>
</template>

<script>
import test from '~/plugins/helper.js'

export default {
  computed: {
    getTest () {
      return test()
    }
  }
}
</script> 

Upvotes: 4

Related Questions