Using Nuxt.js to incorporate the lodash library

I recently started experimenting with Nuxt.js, but I'm having trouble understanding how the plugins system works.

In my nuxt.config.js, I've added the following plugin:

// Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins
plugins: [
  '~/plugins/lodash',
],

After creating a file named lodash.js in the plugins directory with the code snippet:

import Vue from 'vue';
import lodash from 'lodash';

Vue.use(lodash);

When trying to access this.lodash in my component, it returns undefined. Additionally, attempting to use methods like

this.lodash.pick(['a'], { a: 'a', b: 'b' })
throws an error. That's when I attempted using this.$lodash, which returned ƒ and further logging produced a LodashWrapper object.

Thinking that maybe using Vue.use() wasn't the right approach, I modified the plugin file to inject lodash like this:

import lodash from 'lodash';

export default({ app }, inject) => {
  inject('lodash', lodash);
}

However, this change didn't yield any different results. Now I'm stuck and unsure of what to do next. How can I properly install and utilize lodash, or any other npm module, in a Nuxt.js project?

For reference, my project is running on Nuxt version 2.14.12.

Answer №1

I recently successfully integrated the lodash library into my Vue project by following Atif Zia's recommendation on Stack Overflow and using the vue-lodash package.

To add lodash, I created a new file named plugins/lodash.js with the following content:

import Vue from 'vue'
import VueLodash from 'vue-lodash'
import lodash from 'lodash'

Vue.use(VueLodash, { name: '$_', lodash })

In the configuration file nuxt.config.js, I included the newly created plugin under the plugins array:

export default {
...
plugins: ['~/plugins/lodash.js'],
...
}

After setting up the plugin, I utilized lodash in my script to manipulate objects like so:

var object = { 'a': 1, 'b': '2', 'c': 3 };
 
this._.pick(object, ['a', 'c']);
// => { 'a': 1, 'c': 3 }

The vue-lodash package seems to ensure that lodash is webpacked correctly based on my findings on their GitHub repository.

Answer №2

Hello @PrintlnParams, you have a couple of options to achieve this functionality. One way is to utilize the vue-lodash package and use this.$_.sumBy(). Alternatively, you can import lodash by using import _ from "lodash" or import individual components such as

import { sumBy } from "lodash"
when working with Nuxt.Js.

Answer №3

Here is a quick guide on how to locally import Lodash into your Nuxt project.

<script lang="ts" setup>
import _ from 'lodash'

const data = [{ name: 'B' }, { name: 'A' }, { name: 'C' }]
const sortedData = _.orderBy(data, ['name'], ['asc'])
console.log(sortedData)
</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can you retrieve the input value in JavaScript when the cursor is not focused?

Here is an input I am working with: <a-form-item label="user" :colon="false"> <a-input placeholder="user" name="user" @keyup.enter="checkUser"/> </a-form-item> Within my methods: chec ...

Using Vue.js: Load component only after user's button click

I need some help with my code setup. I want to make it so that the components "dataPart1' and "dataPart2" are not loaded by default, but only appear when a user presses a button to view the data. How can I achieve this functionality in Vue.js? var ap ...

Guide to placing an icon next to a label with Vue Bootstrap

I'm working with a Vue Bootstrap input field setup like this: <b-form-group label="Name" label-for="name"> <validation-provider #default="{ errors }" name="Mapping Name" rules="required ...

Align a button to the left or right based on its position within the layout

On the left side, there is dynamic text and on the right side, a button is displayed as shown below: <div class="dynamic-text"> {{ dynamicText }} </div> <div class="some-button"> < ...

how to switch page direction seamlessly in vue without triggering a page refresh

I'm looking to update the page direction in Pinia whenever a value changes, and while my code is functioning correctly, it reloads the page which I want to avoid. Take a look at my App.vue <script setup> import { useaCountdownStore } from " ...

Is Nuxt's FingerprintJS Module the Ultimate Server and Client Solution?

I am currently using fingerprintJS in my NuxtJS+Firebase project VuexStore. When I call the function on the client side, I can retrieve the Visitor ID. However, I am encountering issues when trying to use it on the server side, such as in nuxtServerInit. ...

Guide on utilizing Vue to trigger an API call when the input box loses focus

I am currently facing challenges while trying to learn vue, and I am not sure how to proceed. I would greatly appreciate any assistance! To begin with, I want to acknowledge that my English may not be perfect, but I will do my best to explain my issue tho ...

Incorporating a new element through the simple act of clicking a

Vue.component('component-a', { template: '<h3>Hello world!</h3>' }) new Vue({ el: "#app", data: { arr: [] }, methods: { add(){ this.arr.push('component-a'); console.dir(this.arr) ...

Having trouble looping through an array of objects containing images in Javascript?

I am currently facing challenges with iterating through an array of objects that contain images. The array appears empty when logged in the console, but upon inspecting it in the console, I can see all the objects along with their iteration numbers. I have ...

Is it possible to pass a prop down through 2 levels of nested children components?

I am facing an issue with passing a prop in my component. The id is passed as a prop like this: <comments myId="1"></comments> In the comments component, I have defined the prop like this: props: [ 'myId', ], Within the commen ...

Can we create dynamic v-for variables in Vue.js?

<div class="col-3" v-for="n in 5" :key="n"> <h3>Table {{n}}</h3> <draggable class="list-group" :list="`list${n}`" group="people" @change="log"> ...

The error thrown is Uncaught TypeError: 'this' is not defined in the Vuex

<script setup> import { useLayout } from '@/layout/composables/layout'; import { ref, computed ,onMounted} from 'vue'; import AppConfig from '@/layout/AppConfig.vue'; import auth from '@/auth'; const { layoutC ...

Issue with vue transition not functioning as expected when hiding a div

I'm having an issue with a simple transition that toggles the visibility of a div text. The transition only seems to work when hiding the text, but not when showing it. Here's my code: <template> <div> <transition name="fa ...

Learning how to handle URLEncoded format in Vue JS

Seeking guidance on how to handle URL Encoded format in postman to send data to my Vue JS app. Using the encoded format shown below, what npm package should I utilize for this task? https://i.stack.imgur.com/sBkXi.png ...

Keep Me Logged In Option for User Authentication

My Login Component features a form with 2 fields and a remember me checkbox. I want to implement functionality so that when the checkbox is checked, it remembers the email and password. <form> <div class="form-group-custom"> <label for=" ...

Attempting to automatically invoke the API every minute, rather than relying on the user to reload the page

I currently have fetchCoins() in my mounted() function, which calls the API whenever a user refreshes. My goal is to call the API once, store the data in local storage, and then retrieve the data every minute. methods: { async fetchCoins() { con ...

Encountering an error while setting up the object spread operator Babel plugin for ES201

Exploring the possibilities of the new ES2018 spread operator for objects led me to discovering a promising NPM package: babel-plugin-transform-object-rest-spread Here's a glimpse of my package.json: // Scripts section "scripts": { "dev": " ...

Having trouble with Vue component not showing updated data after axios POST request issue

Hi there, I'm facing an issue and could really use some guidance from a skilled Javascript Wizard. Here's the problem: I have a Laravel collection that I'm passing to a Vue component. Within the component, I am looping through the collecti ...

The process of downloading an image from Spring Boot using VueJs and displaying it within an <img> tag

I have created a Spring Boot backend with a Vue frontend. I am having issues when trying to download and display an image from Google Cloud Storage in my application. Sometimes the downloaded image appears to be cut off, as if not all bytes were sent. Howe ...

Launching a Component Using the Menu Feature in VueJS 3

I'm not particularly versed in frontend development, but I'm facing a bit of a challenge. I have a menu with an option labeled "VIEW PROFILE," and I want it to open another vue file I created with user information when clicked. The slide-out func ...