Incorporate additional libraries like jQuery into your Vue.js application

I am facing an issue with connecting a third-party js library to a vue.js component

main.js

...
require('jquery')
import Vue from 'vue'
import VueMdl from 'vue-mdl'
import App from './App'
import Auth from './views/user/Auth'
import Index from './views/Index'
import VueRouter from 'vue-router'
import VueResource from 'vue-resource'

Vue.use(VueRouter)
Vue.use(VueMdl)
Vue.use(VueResource)

const AppComponent = Vue.extend(App)
new AppComponent({
  router,
  el: '#app',
  template: '<App/>',
  components: { App }
})

RegisterModal.vue

<template>
  ...
</template>

    <script>
      export default {
        name: 'register',
        data () {
          return {
            msg: 'Register'
          }
        },
        methods: {
          open () {
            this.$refs.register.open()
          },
          close () {
            this.$refs.register.close()
          },
          submit () {
            var data = $('form').serialize() //  '$' is not defined
            console.log(jQuery) // 'jQuery' is not defined
            console.log(data);
          }
        }
      }
    </script>

require with webpack

plugins: [
new webpack.ProvidePlugin({
$ : "jquery",
jQuery : "jquery",
})
],

The above approach did not work for me

What is the solution to resolve my problem and successfully utilize any library within the vue.js component?

Answer №1

Declaration of jQuery globally appears to be necessary, you can do so by:

new webpack.ProvidePlugin({
    $: "jquery",
    jQuery: "jquery",
    "window.jQuery": "jquery"
});

Alternatively, you can also declare it as:

window.$ = window.JQuery = require('jquery');

Answer №2

Step 1: Include $ in RegisterModal.vue file.

<script>
  import $ from 'jQuery';
</script>

Step 2: Update webpack.config.js with the externals configuration.

externals: {
      jQuery: 'window.jQuery'
 }

Answer №3

While encountering a similar problem, I stumbled upon this informative article that proposes the following solution:

The most effective and reliable way to integrate a Javascript library into a Vue project is by proxying it to a property of the Vue prototype object. Let's implement this method to incorporate the Moment date and time library into our project: (entry.js)

import moment from 'moment';
Object.defineProperty(Vue.prototype, '$moment', { value: moment });

The author elaborates on this approach:

Because all components inherit their functionalities from the Vue prototype object, implementing Moment in this manner enables its automatic availability across all components without the need for global variables or manual imports. It can easily be accessed within any instance/component using this.$moment.

After some experimentation, I successfully implemented this technique, such as utilizing props in a child component:

<p v-if="enrolment.eventBookings.length > 0">{{$moment(enrolment.eventBookings[0].bookable.startTime).format("HH:mm")}}</p>

Hats off to the author for sharing this valuable insight!

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

"Trying to upload a PDF file with ajax, but encountering consistent failures with

I've been struggling with this code that just won't work as intended. I'm attempting to send file data and an ID to the php side, but it's failing consistently. I can't figure out what mistake I'm making. Any help would be gre ...

Attaching an event handler to $(document) within an Angular directive

One of the challenges I am facing is creating a directive that functions like a select box. When this select box is open and I click outside of it (anywhere else on the document), I want it to collapse. Although this JQuery code works within my directive, ...

SystemJS could not locate the root directory for RxJS

There seems to be an issue with SystemJS loading rxjs modules on Windows, as it throws a 404 Not Found error on the rxjs directory. This problem does not occur on OSX, and all modules are up to date. GET http://localhost:8080/node_modules/rxjs/ 404 (Not F ...

Iterate through an array containing objects that may have optional properties, ensuring to loop through the entire

I need help iterating through an array of objects with a specific interface structure: export interface Incident { ID: string; userName1?: string; userName2?: string; userPhoneNumber?: string; crashSeverity: number; crashTime: number; } Here ...

Check to see if the moment function has been executed and if the resulting output is accurate

I have a function called moment that formats a date received from the server in milliseconds. I am attempting to write tests using Enzyme and Jest to check if the moment function has been called (1), and whether the output of the function matches the expec ...

The CORS policy is blocking Django Vue Js Axios from functioning as expected

Utilizing Django as the backend and Vue as the frontend, I am using axios to send a request from Vue to Django. I have encountered CORS policy blocking even after trying various solutions. I have spent approximately 4 hours Googling and still facing this ...

Facing a problem with the carousel in Angular 6

I am currently working with Angular 6 and I have a topAdvertisementList[] that is supposed to return 2 records to be displayed in my carousel with a fixed image, but for some reason, only one record is showing up in the carousel! I suspect there might be a ...

Challenges with parsing JSON using jQuery

I am attempting to retrieve data from a page that returns JSON in order to store it in an array. The current code is functional, but I am encountering difficulties when trying to pass the variable (which should contain the content) into the jQuery.parseJSO ...

Combining Angular variables within HTML tags: A Guide to AngularJS

As a newcomer to AngularJS, I am truly impressed by its capabilities. One thing I am eager to learn is how to include an AngularJS binding within an HTML attribute, while also adding another string to it. I often use unique names like "thisform" and "thisd ...

Tips for incorporating various Vue Js components into an outdated system

I have an old Java system with multiple pages that includes a Vue dashboard component on App.vue. The issue arises when I try to use Vue on another page without wanting the dashboard to appear there as well. After researching, I found conflicting informat ...

Exploring the orderBy feature in the react-firebase-hooks library with NextJS

Recently, I've been utilizing the React Firebase Hooks package from this GitHub repository. The code snippet below has been functioning smoothly for me. const [posts, loading, error] = useCollection( firebase .firestore() .collection(& ...

JSON autocomplete feature for text input field

I've been struggling to implement an autocomplete textbox that utilizes a JSON file as its data source. Currently, the app is hosted on Google App Engine and the autocomplete function is based on an array of countries hardcoded into the code. However, ...

Find the second element beneath the mouse cursor that is not a direct ancestor of the first element

I am currently developing a card drag-and-drop board using HTML5 inspired by Trello. My focus right now is on connecting the lists to specific list slots/containers. My challenge lies in determining which list container is positioned beneath the mouse po ...

Unable to render a rectangle with React's canvas context.fillRect

Could anyone help me with drawing a rectangle using React? I'm having trouble getting it to work. I'm confused as to why the code below isn't showing a rectangle on the screen. class DrawingView{ constructor(props) { this.canva ...

The absence of variable declaration in a 'for...of' loop is functional in .js files but does not work in

index.js let items = [{ item: 'apple' }, { item: 'banana' }, { item: 'orange' }]; for (item of items) { console.log(item); } Execute using node $ node index.js { item: 'apple' } { item: 'banana' } { ...

Tips for retrieving the ID of a dynamic page

In my Higher Order Component (HOC), I have set up a function that redirects the user to the login page if there is no token. My goal is to store the URL that the user intended to visit before being redirected and then push them back to that page. However, ...

"Successfully making AJAX calls on localhost, but encountering issues when trying to make them online

Whenever a visitor navigates to a specific page (referred to as page1), the PHP script is initiated to load the HTML content for an array that contains data about the users. After the page has finished loading (DOM ready), I utilize jQuery to make an AJAX ...

JavaScript node failing to update variable value with promise value

I am facing an issue with the following code snippet- let { user } = req.body; let name = null; if (!user) { getStudent(id).then((x) => { user = x.user; name = x.name; }); } console.log(user, name); // prints undefined and null Despite us ...

Setting a global variable in the JavaScript code below

Is there a way to make the modal variable global by setting it as var modal = $("#modal"); ? The code snippet below includes the modal variable and is not functioning properly. It needs to work correctly in order to display: "Hello name, You have signed u ...

Improving the method: 'Avoid altering vuex store state without using mutation handlers' errors

Starting Point: Everything is running smoothly in my application, but I'm interested in exploring alternative solutions to the problem I encountered. Situation: Currently, I am in the process of implementing a Permission System for a project. The wor ...