Search code examples
vue.jswebpacklodash

How to import lodash single function and use on Vue.js template?


I tried to import a single Lodash function inside my Vue.js component, like this:

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

<script>
import isEmpty from "lodash/isEmpty"

export default {
    data () {
        return { example: "Some text" }
    }
}
</script>

But when I use it inside the template it gives this error:

[Vue warn]: Property or method "isEmpty" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property.

I have this lodash entry in my package.json file:

"dependencies": {
    "lodash": "^4.17.11"
}

Solution

  • I think your options are either to pass the function through data:

    export default {
        data () {
            return { 
                isEmpty: isEmpty,
                example: "Some text",
            }
        }
    }
    

    or to make a computed property:

    <span v-if="!exampleTextEmpty">{{example}}</span>
    
    // ...
    
    export default {
        data () {
            return { example: "Some text" }
        },
        computed: {
            exampleTextEmpty() {
                return isEmpty(this.example);
            }
        }
    }