Just started using Nuxt.js a week ago and I'm not getting the hang of the plugins system.
The relevant part of my nuxt.config.js looks like this:
// Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins
plugins: [
'~/plugins/lodash',
],
And I created a file named lodash.js in the plugins directory that looks like this:
import Vue from 'vue';
import lodash from 'lodash';
Vue.use(lodash);
But then in my .vue component, when I console.log('lodash:', this.lodash), it prints out lodash: undefined, and when I try to use this.lodash.pick(['a'], { a: 'a', b: 'b' }), for instance, it throws the error: TypeError: Cannot read property 'pick' of undefined.
So then I tried using this.$lodash (added an $), and when I then console.log('lodash:', this.$lodash), it logs lodash: ƒ, and using console.log('lodash:', this.$lodash()) (calling it like a function) logs lodash: LodashWrapper {__wrapped__: undefined, __actions__: Array(0), __chain__: false, __index__: 0, __values__: undefined} (i.e. an object with a bunch of worthless properties).
So then I thought maybe Vue.use() isn't the way to go and maybe I should instead inject lodash, so I changed up my lodash.js plugin file to look like this:
import lodash from 'lodash';
export default({ app }, inject) => {
inject('lodash', lodash);
}
But that led to exactly the same results. And now I don't know what else to try. So my question is how do you install and use lodash (and I suppose any other random npm module) in a nuxt.js project?
FWIW my project's running nuxt version 2.14.12
I've achieved adding lodash into this.$_ using Atif Zia's reccomendation of vue-lodash.
plugins/lodash.js:
import Vue from 'vue'
import VueLodash from 'vue-lodash'
import lodash from 'lodash'
Vue.use(VueLodash, { name: '$_', lodash })
nuxt.config.js:
export default {
...
plugins: ['~/plugins/lodash.js'],
...
}
Usage in script:
var object = { 'a': 1, 'b': '2', 'c': 3 };
this._.pick(object, ['a', 'c']);
// => { 'a': 1, 'c': 3 }
Looking at their GitHub, it looks like this package allows lodash to be webpacked properly.
Hi @PrintlnParams you can eigther use vue-lodash package to achieve
this.$_.sumBy().
or you can import lodash as
import _ from "lodash"
or individual components as
import { sumBy } from "lodash"
to use with Nuxt.Js
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With