Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

vuejs2

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'
}
like image 236
shak imran Avatar asked Oct 18 '17 08:10

shak imran


3 Answers

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()
like image 116
Ali Gilan Avatar answered Sep 19 '22 15:09

Ali Gilan


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

like image 44
manAbl Avatar answered Sep 23 '22 15:09

manAbl


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.

like image 34
SanBen Avatar answered Sep 23 '22 15:09

SanBen