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

Tips on sending non-form values to an action in Struts 1.3 via AJAX

Here is a snippet of JSP code that I am working with: <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%> < ...

What sets Fetch Promise apart in terms of delivery success?

Struggling with using strapi in my project, as the fetch function returns a promise instead of JSON data This is my code : const [products, setProducts] = useState([]); useEffect(() => { (async () => { try { l ...

Discover the methods for accessing an array of IDs by implementing an event trigger in conjunction with checkboxes

Can you assist me with a dilemma I'm facing? I've developed a static form containing numerous checkboxes and checklists. My challenge arises when trying to integrate a JavaScript code that automatically selects subcategories when parent checkboxe ...

Step-by-step guide on starting Edge with Open package on Windows 10

I am utilizing the Open package to launch URLs across different browsers. Unfortunately, there is a lack of comprehensive documentation on how to specifically launch with different browsers on various operating systems. After some experimentation, I have ...

"Using HTML to assign a unique identifier to an image within

Apologies in advance for any errors as I am relatively new to html. I am attempting to construct a table with images that have onclick events, so that each clicked seat is tracked and its id is added to a list to change the class. Each image has been give ...

Karma Jasmin is puzzled as to why her tests are failing intermittently, despite the absence of any actual test cases

In this snippet, you will find my oninit method which I am instructed not to modify. ngOnInit(): void { this.setCustomizedValues(); this.sub = PubSub.subscribe('highlightEntity', (subId, entityIdentifier: string) => { ...

Ensure the backslashes are removed from the AWS Lambda string API response

I have an AWS Lambda function where I am sending a string as my final response let abc= `"phone_exist":"0","calls":"0","lastaction":"0"` callback(null,abc); Output: "\"phone_exist\":\"0\",\"calls\":\"0\",\"l ...

What is the Typescript definition of a module that acts as a function and includes namespaces?

I'm currently working on creating a *.d.ts file for the react-grid-layout library. The library's index.js file reveals that it exports a function - ReactGridLayout, which is a subclass of React.Component: // react-grid-layout/index.js module.exp ...

Tips for utilizing bootstrap.css to position a web design form in the center of the page and place the copyright at the bottom

I have spent several hours trying to figure out how to achieve this, but still haven't found the solution. I have a form that I believe doesn't look very good: So, I attempted to center the form on the page and place the footer.php at the botto ...

Upon implementing a catch-all express routing solution, the Fetch API calls are no longer successful. The error message received is "Unexpected token < in JSON at

While working on a React project, I encountered an issue outlined in this link: React-router urls don't work when refreshing or manually typing. To resolve this problem, I decided to implement the "Catch-All" solution recommended in that discussion. ...

Convert JavaScript object into distinct identifier

I have a data object where I'm storing various page settings, structured like this: var filters={ "brands":["brand1","brand2","brand3"], "family":"reds", "palettes":["palette1","palette2","palette3"], "color":"a1b2" }; This object is ...

Step-by-step guide to aligning layout using material design in generator-gulp-angular

I am currently using generator-gulp-angular with angular-material-design and ui-router All views are loaded into index.html in the <div ui-view></div> element However, when I attempt to center the element with material design directives insid ...

Display the div according to the $index selected from the AngularJS list

Below is the structure of my HTML code: <div class="col-md-4"> <ul class="list-group text-left"> <a href="#" class="list-group-item" ng-click="showData($index)" ng-repeat="field in Data"> {{ field.name }}</a> ...

Tips for dynamically accessing object properties in TypeScript

I've been going through the process of converting existing Node.js projects to TypeScript. As part of this, I am utilizing the http-status package (https://www.npmjs.com/package/http-status) for handling HTTP status codes. While trying to pass varia ...

Issues with Angular not reflecting data changes in the view after updates have occurred

I have a setup with two components. One is responsible for creating new data entries, while the other one is in charge of listing all the data stored in a database. The issue I'm facing is that even though the creation component successfully adds new ...

Using Jquery to set up an event listener on a child div that changes the CSS property of its parent div

I am currently working on a product customization form where the radio buttons are hidden using opacity:0. My goal is to have the border of the image turn black when an option is selected as a visual feedback for the user. I've implemented an event l ...

The preventDefault() function is not functioning properly on the <a> tag

As a JavaScript beginner, I decided to create an accordion menu using JavaScript. Although I was successful in implementing it, I encountered a bug in my program. In this scenario, uppercase letters represent first-level menus while lowercase letters repr ...

Identify unique special characters without the need for a specific key code

When you press the backspace key, the console may display an empty string for keyVal, which can be misleading because even though it appears empty, keyVal.length is actually equal to 1 due to a hidden character. element.on('keydown',function(e){ ...

The functionality of react-router-dom's NavLink isActive feature seems to be unreliable

We are currently immersed in a React.js project. I am in the process of setting up multiple pages using react-router-dom and my goal is to alter the active icon by using NavLink. The icon+sel signifies the active page. render() { const oddEvent = (mat ...

Building a High-Performance Angular 2 Application: A Comprehensive Guide from Development to

Recently, I began developing an Angular2 project using the quickstart template. My main concern now is determining which files are essential for deployment on my live server. I am unsure about the specific requirements and unnecessary files within the qu ...