Using lodash in all of vue component template

antoniputra picture antoniputra · Jun 8, 2016 · Viewed 70.2k times · Source

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()

Answer

anthonygore picture anthonygore · Apr 22, 2017

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.