Using lodash in all of vue component template

JavascriptLodashvue.jsVue Component

Javascript Problem Overview


Can I use lodash _ in all of my vue component?

for example:

I have components organized like below:

App.vue > Parent.vue > Child.vue

I would like all of my component to access _ lodash without defined in every component vm data

===

I am also trying using Mixins. it works. but the result not expected like this _().isEmpty() instead of _.isEmpty()

Javascript Solutions


Solution 1 - Javascript

Some of the current answers may work in your scenario, but they have downsides:

  • Adding to the window object means your Vue project can't be server rendered, because servers don't have access to the window object.
  • Importing in every file works fine, but it can be a pain if you have to remember to do it in every file.

An alternative approach is to add your library to the Vue prototype. All components inherit from this so they will now all be able to access your library from the this keyword.

import _ from 'lodash';    
Object.defineProperty(Vue.prototype, '$_', { value: _ });

Now lodash is available as an instance method for all components. In a .vue file you can do this without importing anything:

export default {
  created() {
    console.log(this.$_.isEmpty(null));
  }
}

The advantage of using Object.defineProperty rather than a normal property assignment is that you can define a descriptor which allows you to make the property read-only, which it will be by default. This stops consuming components from overwriting it.

This is more thoroughly explained in this blog post (which I wrote).

Note: The downside to this approach is that you get the entire Lodash library, even if you only need one or two functions. If that's a problem, best to use import { reduce, whatever } from "lodash"; at the top of the file requiring it.

Solution 2 - Javascript

You could import the lodash into each component:

<script>
  import _ from 'lodash'

  export default {
    methods: {
      test (value) {
        return _.isEmpty(value)
      }
    }
  }
</script>

Solution 3 - Javascript

For inline templates separated from the js module code it should work with:

  Vue.component('some-tag', {
    computed: {
      _() {
        return _;
      }
    }
  });

And then you can use it in template in "native" way - _.isEmpty(value).

Solution 4 - Javascript

import _ from 'lodash'
Vue.prototype._ = _

Insert these lines in your main.js file and it will work all over your app.

Solution 5 - Javascript

You could import lodash globally like this

window._ = require('lodash');

Once that has been imported, you will have access to _ from anywhere.

Solution 6 - Javascript

A simple approach that worked for me:

Vue.set(Vue.prototype, '_', _);

This should allow you to use _ in all component templates and vue instances.

Solution 7 - Javascript

You can use plugin/mixin like this.

import _ from 'lodash';
exports default {
    install : function(Vue, options){
        Vue.mixin({
            computed : {
                "_" : function(){
                    return _;
                }
            }
        });
    }
}

Solution 8 - Javascript

Bit late to the party but through my research of finding a way to import lodash and other libraries into all my .vue files, I encountered the webpack ProvidePlugin, which achieves everything the OP requested with almost no fuss. To implement this solution, following this fantastic tutorial.

I would note that in the tutorial, he left import "jquery" in his app.js file, which is not required. The plugin with import it automatically.

Solution 9 - Javascript

Check out vue-lodash!! It's a new wrapper for using lodash in vue. You can call it using

> Vue..random(20) // for getting random number between 20 > > this..random(20) //or other method you want to use

in any of the component file :)

Solution 10 - Javascript

You can also create a base component and make all of your components extend it.

// base-component
import _ from 'lodash';

export default Vue.extend({
  computed: {
    _() {
      return _;
    },
  },
});
// my-component
import BaseComponent from 'path/to/base-vue';

export default BaseComponent.extend({
  template: '<p>Lodash is available: {{!!_}}</p>'
  methods: {
    doSomehting() {
      // `this._` should be available
    },
  },
});

The pro of this approach is it's not intrusive, so no possible conflict with Vue in the future. Also, you can add even more things to the BaseComponent, like other libraries and external services, and they will be available to all other components.

The con is it's more verbose and you have to remember to inherit from the base component.

Solution 11 - Javascript

For vue users

Go to main.js

import _ from 'lodash'
Vue.set(Vue.prototype, '$_', _)

For nuxt.js users

create main.js inside plugin folder

plugin/main.js

import _ from 'lodash'
Vue.set(Vue.prototype, '$_', _)

Then add into nuxt.config.js

  plugins: ['~plugins/main.js'],

usage are same in both vue and nuxt js

then use in component

this.$_.map(arra,(x)=>{})

Solution 12 - Javascript

The proper way is to use provide / inject as such:

import _ from 'lodash';

const app = createApp({
        provide: {
            $_: _,
        }
    });

Then in аnоthег component:

<script>
    export default {
        name: 'аnоthег-component',
        inject: [
            '$_'
        ]
    }
</script>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionantoniputraView Question on Stackoverflow
Solution 1 - JavascriptanthonygoreView Answer on Stackoverflow
Solution 2 - JavascriptPantelis PeslisView Answer on Stackoverflow
Solution 3 - JavascriptgorodezkiyView Answer on Stackoverflow
Solution 4 - JavascriptbutaminasView Answer on Stackoverflow
Solution 5 - JavascriptBrandon FerensView Answer on Stackoverflow
Solution 6 - Javascriptnewms87View Answer on Stackoverflow
Solution 7 - JavascriptHotbrainsView Answer on Stackoverflow
Solution 8 - Javascriptp4tView Answer on Stackoverflow
Solution 9 - JavascriptEwingView Answer on Stackoverflow
Solution 10 - JavascriptLeonardo RaeleView Answer on Stackoverflow
Solution 11 - JavascriptßãlãjîView Answer on Stackoverflow
Solution 12 - JavascriptMaxView Answer on Stackoverflow