12

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

6 Answers 6

23

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()
Sign up to request clarification or add additional context in comments.

Comments

10

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.

Comments

4

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> 

1 Comment

How to import globally rather than importing into each page.
3

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

Comments

1

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}

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.