Guide on Implementing jQuery Plugin with Vue, Webpack, and Typescript

I am currently exploring the integration of the jQuery Plugin Chosen into my vue.js/Webpack project with TypeScript.

After some research, I discovered that it is recommended to encapsulate the plugin within a custom Vue component.

To kick things off, I made sure to install the necessary NPM packages:

npm install jquery --save
npm install @types/jquery --save
npm install chosen-js --save
npm install @types/chosen-js --save

Next, let's take a look at my Vue component:

<template>
    <select>
        <option value="1">Test1</option>
        <option value="2">Test2</option>
    </select>
</template>

<script lang="ts">
    import { Component, Prop, Vue } from "vue-property-decorator";
    import $ from 'jquery';    
    import 'chosen-js';

    @Component
    export default class ChosenSelect extends Vue{
        @Prop()options!:string;
        @Prop()value!:string;

        mounted() {
            let vm = this;
            let el = $(vm.$el);
            console.log(el);
        }
    }
</script>

So far, everything seems to be in order. However, when attempting to utilize the Chosen functionality by adding import 'chosen-js', I encountered an issue where I received a

Uncaught ReferenceError: jQuery is not defined
error from the chosen library.

My ultimate question now becomes: What is the proper approach to importing both jQuery and chosen-js while effectively using them within a Vue Typescript component?

Answer №1

I was able to find the solution thanks to this helpful article

First, make sure to install jquery:

npm install jquery --save
npm install @types/jquery --save

Next, add the following to any of your components:

import * as $ from 'jquery';

To test if jquery is working correctly, you can try something like this:

import * as $ from 'jquery';

export default class Home extends Vue {
  created () {
    this.test()
  }

  test () {
    console.log($('body'))  // It's work
  }
}

Sometimes it may be necessary to wait for the DOM to be fully loaded before using jquery:

<template>
  <div class="home">
    <div id="test">wijfwoe</div>
  </div>
</template>

<script>
import * as $ from 'jquery';
export default class Home extends Vue {
  created () {
  }

  mounted () {
        let a = $('#test')[0];
        console.log(a.textContent);
  }
</script>

Answer №2

Adding this code snippet to the main.ts file will ensure that it is accessible within all components.

declare global {
    interface Window { $: any; }
}
window.$ = require('jquery')

Answer №3

Instead of relying on a jQuery-based select plugin, I recommend using a Vue-specific one to maximize the benefits of utilizing Vue for DOM manipulations. Many of these plugins come with their own components, eliminating the need for creating a wrapper.

If you're looking for Vue resources beyond just plugins, check out this curated list: awesome-vue

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

What is the best way for Flask to host the React public files?

When working with React, I created a folder called ./public/assets, and placed an image inside it. Running npm start worked perfectly fine for me. However, after running npm run build in React, I ended up with a ./build folder. To solve this issue, I moved ...

Tips for correctly passing the appropriate data type using generics in TypeScript

If I have an array of objects with a key called render, which may be an optional function that takes a parameter (unknown type) const objectArray = [{a: 1}, {b: 2, render: renderFunction}, {c: 3, render: anotherFunction}] suppose the second object's ...

Why is my Vue view not being found by Typescript (or possibly Webpack)?

npx webpack TS2307: Cannot locate module './App.vue' or its corresponding type declarations. I am currently utilizing webpack, vue, and typescript. My webpack configuration is pretty basic. It uses a typescript file as the entry point and gener ...

Inference of generic types within a TypeScript generic

In my coding journey, I came across a situation where I was dealing with generic classes. Specifically, I had a Generic class Generic<T> and another one called GenericWrap that used Generic as its maximum type parameter (denoted as U extends Generic& ...

AngularJS issue: Unable to reset scope variable

I am facing an issue with a function in my angularJS controller that is triggered on a dropdown option change: Currently, when a default option is selected, the corresponding records from the database are fetched and set to a scope variable. Everything s ...

Issue with AJAX MVC HTML: jQuery value is not blocking API call

Upon clicking a button, I am triggering a web API call using AJAX. My form is utilizing JqueryVal for form validations based on my viewmodel data annotations. The issue I am facing is that when I click the "Listo" button in my form, it executes the API ca ...

Tips for updating the selected value in Vue dynamically

I am currently working on a feature where the months change dynamically based on the selection made using Vue. You can view the code snippet in the link provided below. <div id="app"> <span class="selectboxWrap"> < ...

Discovering the position of elements in relation to their (grand^N)parent

Among my possessions are elements A and B. B has the ability to exist as a direct child of A, or there may be anywhere from 0 to N elements separating them. It is imperative that I determine how B is situated in relation to A, specifically noting the dist ...

Using ExpressJS and Jade to submit a form using the POST method and redirecting to a specified path

I am exploring node, express and jade for the first time and working on a small application that requires users to enter their name and password in a form. The app then redirects them to a path based on their username. Here is the code snippet to achieve ...

Ways to avoid automatic error correction when running npm lint?

Utilizing the Vue CLI, I developed a Vue3 app with a Prettier/Eslint configuration. Upon making changes to the main.ts file as shown below: import { createApp } from "vue"; import App from "./App.vue"; import router from "./router& ...

Trouble with importing css in Angular webpack due to ui-bootstrap integration

Currently, I am developing an Angular application with Webpack and was looking to incorporate Bootstrap for styling purposes. To achieve this, I first installed 'ui-bootstrap' using npm install angular-ui-bootstrap --save-dev. After installation ...

What is the best way to set the `value` attribute and `v-model` attribute for a custom Vue component?

I am seeking to develop a unique Vue component that functions as a "radio div" - essentially, a div with the ability to act like a radio button where only one among multiple can be selected at a time. The div will also have a slot for including any desired ...

What could be causing a parse error and missing authorization token in an AJAX request?

I recently wrote some code to connect a chat bot to Viber using the REST API. The main part of the code looks like this -: $.ajax({ url : url , dataType : "jsonp", type : 'POST', jsonpCallback: 'fn', headers: { 'X-Viber-Auth- ...

Encountering an endless loop while attempting to retrieve data from Firebase in Next.js through the use of useEffect

Currently, I am in the process of setting up a video section for a project using NextJS. The videos are stored in firebase storage. I have implemented a dynamic route that retrieves all videos from a specific reference within the bucket. For instance, if ...

Why does it fire off numerous requests even though I only called it once?

Everything seemed to be working fine with my project. However, I noticed in the console network that one of my GET requests is being sent twice even though I only triggered it once. View network console here If I comment out the entire created function co ...

The ScrollToTop feature in MUI component seems to be malfunctioning when paired with the useScrollTrigger hook

I am in the process of developing a custom ScrollToTop component using MUI's useScrollTrigger hook. More information can be found at this link Feel free to check out the sample code here: https://codesandbox.io/s/stackoverlow-mui-usescrolltrigger-er9 ...

The getMonthlyBalances function is providing inaccurate results when calculating stock balances

One of my functions is called getMonthlyBalances, which takes in two arrays - stocks and trades. It calculates the monthly balance of a user's stock holdings based on their trade history. The stocks array includes objects with stock ID, prices, and da ...

The specified type cannot be assigned to the type 'IntrinsicAttributes & MoralisProviderProps'

I'm brand new to TypeScript and I have a question about setting initializeOnMount to true. Why does it only allow me to set it to false? Here is the error message: Type '{ children: Element; appId: string | undefined; serverUrl: string | undefine ...

Adapting imports in Typescript for seamless npm distribution

Currently, I'm facing an issue with module resolution while compiling my NPM package written in Typescript for publishing. In my project, I've been using non-relative imports to avoid the hassle of excessive ../../../. However, according to TypeS ...

Set a cap on the number of ajax autocomplete suggestions displayed

Is there a way to limit the number of search results without using local data? I know it's easy to do with local data as shown below: source: function(request, response) { var results = $.ui.autocomplete.filter(myarray, request.term); respon ...