Using lodash in all of vue component template

You could import the lodash into each component:

<script>
  import _ from 'lodash'

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

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.