[Vuejs]-Why is lodash not working when I import it in Vue.js

3๐Ÿ‘

โœ…

Youโ€™ll still need to access the prototype via the this context, like this._.map().

computed: {
  hidecompletedtask() {
    return this._.map(this.tasks, (val) => {
      return !val.done;
    });
  }
}

Reference: Adding Instance Properties.


Alternatively, you could extend the global window object. Put the following line in your main.js (or some booting file).

window._ = require('lodash');

Somewhere else where you need the library:

computed: {
  hidecompletedtask() {
    // The underscore (_) character now refers to the `window._ object`
    // so you can drop the `this`.
    return _.map(this.tasks, (val) => {
      return !val.done;
    });
  }
}
๐Ÿ‘คYom T.

1๐Ÿ‘

You can also use vue-lodash package โ€” Follow these steps:

  1. npm install --save vue-lodash
  2. in main.js โ€” import VueLodash from 'vue-lodash'
  3. in main.js after import โ€” Vue.use(VueLodash)

Usage:

Vue._.random(20);
this._.random(20);

โ€”โ€”โ€“ OR โ€”โ€”โ€”โ€”

In your main.js add this line of code:

window._ = require('lodash');

That way it will work without Vue or this:

Just do โ€” _.map()

๐Ÿ‘คHardik Raval

0๐Ÿ‘

You can import lodash in your main.js file by javascript window object like this:

window._ = require('lodash');

Then use it anywhere in your projet like this:

var original = [
  { label: 'private', value: 'private@johndoe.com' },
  { label: 'work', value: 'work@johndoe.com' }
];

var update = [
  { label: 'private', value: 'me@johndoe.com' },
  { label: 'school', value: 'schol@johndoe.com' }
];

var result = _.unionBy(update, original);
var sortedresult = _map(_.sortBy(result, 'label'));
console.log(sortedresult);

I just use lodash unionBy and sortBy method for example.

๐Ÿ‘คSukanta Bala

Leave a comment