DEV Community

George Jempty
George Jempty

Posted on

Using a Lodash Module Function in a Vue Template

Today when first doing something in an un-Vue like manner, I discovered a neat little trick. In a template I was trying to display something such as:


{{foo.bar.baz}}

The above caused an error due to bar and baz being undefined, and in the end I solved this using v-if="bar && baz". For some reason though to begin with I instead reached for lodash's _.get method (https://lodash.com/docs/#get), something still very useful despite much of lodash's functionality being obsolete today, in my opinion, due to advances in vanilla Javascript.

We already had lodash available to our project so in my component I added:

import _get from 'lodash.get';

Note that from this StackOverflow answer (https://stackoverflow.com/a/43479515/34806) when you import one lodash method you do not access it via the lodash/_ object (i.e. _.get), but rather you can reference it simply as get, though actually I prefer to import it as _get as some indication that it originates with lodash. So I now tried the following in my template:


{{_get(foo, 'bar.baz', ''}}

But I got an error that _get was not available when rendering, which makes sense, I merely imported it, but it wasn't actually a method within my component. So I did the following at the top of methods:

methods: {
    _get,
    // etc.

Tada! Now my usage of the imported method in my template worked. Of course I instantly realized this was a job for v-if but still I think this technique, particularly how to add an imported module method to a Vue component's methods, might be useful.

Top comments (0)