Search code examples
vuejs2lodash

I have error importing lodash in vue file


In my @vue/cli 4.0.5 app I'm trying to import the lodash library, after running npm i lodash

When I try to call isEmpty method I got this error:

Property or method "isEmpty" is not defined on the instance but referenced during render.

Here's how I am importing it in my vue file :

<template>
    <article class="event_item_container">

        <span v-if="!isEmpty(example)">{{example}}</span>

        ...
    </article>
</template>

<script>
    import {bus} from '../../main'
    import axios from 'axios'

    import Vue from 'vue'

    import * as lodash from 'lodash'
    // Vue.use(lodash) // I tried uncomment this line the same error

    // import isEmpty from "lodash/isEmpty" // Aso I tried to uncomment this line, the same error

I tried to import into src/main.js file - the same error...

Which is the valid way?


Solution

  • There are a few things you can try.

    1. Try adding
    import lodash from 'lodash'; 
    Vue.prototype._ = lodash
    

    instead of import * as lodash from 'lodash'. Then try using _.isEmpty.

    1. You can try importing isEmpty like
    import { isEmpty } from 'lodash'; 
    
    1. You can always trying uninstalling lodash (remove from package.json) and then run npm i --save lodash

    EDIT

    As of NPM5 there is no difference between npm install and npm install --save since npm install now adds the package to devDependencies; something it did not do prior to NPM5 (this was why npm install --save was utilized).