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()
Some of the current answers may work in your scenario, but they have downsides:
window
object means your Vue project can't be server rendered, because servers don't have access to the window
object.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.
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