Steps for importing an external .js file into a Vue 2 component

Hello, I am currently working on vue.js 2 and I have come across a problem with the JavaScript part. I would like to include the general.js file in my posts.vue file. Can anyone provide assistance with this? Your help would be greatly appreciated :)

Below is the code snippet:


<template>
    <div>
        <p> {{message}} </p>
    </div>
</template>

<script>
    import axios from 'axios';
    import _ from 'lodash';

    export default {
        data() {
            return {
                message : 'Here is my HTML'    
            }
        }
    }
</script>

Answer №1

To include jQuery in your webpack bundle, you can use the webpack provide plugin. Here is an example configuration:

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

For more information, check out the documentation here.


While it's generally recommended to avoid mixing jQuery with Vue, there are scenarios where you may need to use jQuery within a Vue component. Here's an example:

Let's say you have a simple jQuery plugin called alertText.js:

//define the plugin
$.fn.alertText = function() {
   this.css( "color", "red" );
};

In your component.vue file, you can include and utilize the jQuery plugin like so:

<template>
  <div>
     <p class="alert-me">this text will be changed to red</p>
  </div>
</template>

<script type="text/javascript" src="alertText.js"></script>

<script>
    $('.alert-me').alertText(); // call the plugin on 'alert-me' class
</script>

<script>
    // define your component script
    export default {
         data():{
              //...
          }
     }
</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

Currently, I am compiling a list of tasks that need to be completed, but I am encountering a dilemma that is proving difficult to resolve

Recently delved into the world of Javascript and encountered a roadblock that I can't seem to overcome. Here's the snippet of code causing me trouble: add = document.getElementById("add"); add.addEventListener("click", () => { console.log("Ple ...

Tips for transferring large data without a page redirect using jQuery's post method:

Seeking advice on how to send large data via jQuery POST without redirecting the page. I'm working on a mobile chat project where communication between user app and server is done using JSON. The issue arises when dealing with big data as the jsonGet ...

Vuex: Unable to pinpoint why my getter is failing to sort correctly

store.js getAllCommentsOrderedByTimestamp(state) { let allComments = state.allComments; allComments = allComments.sort((a, b) => { return a.stamped > b.stamped; }); return allComments; } allComments is an array of objec ...

Issue with submitting VueJS form on mobile devices, works fine on web browsers but not on

I have encountered a similar problem before, but I haven't found a suitable solution yet. In my VueJS application, the submit function works perfectly fine on desktop browsers like Chrome and Firefox, but for some reason it refuses to submit on mobil ...

The never-ending scroll feature in Vue.js

For the component of cards in my project, I am trying to implement infinite scrolling with 3 cards per row. Upon reaching the end of the page, I intend to make an API call for the next page and display the subsequent set of cards. Below is my implementatio ...

Using AngularJS: Implementing ng-include with a custom function

When using ng-include, I have encountered a peculiar issue. I am attempting to retrieve the template path by invoking a function defined in the controller that returns the path based on the parameter passed. Below is my code snippet: <tr ng-repeat="det ...

Do not request for this element within the array

I have a function that applies to all elements in an array, except for the currently clicked one. For example: cubesmixed = [array, with, 145, elements] cubesmixed[54].click(function() { for(var i = 0; i < 145; i++) { var randomnumber=Math.flo ...

The datepicker in the jQuery modal dialog is displaying incorrect formatting after a click event

My issue involves a Panel containing an input date field that, upon clicking, should display a datepicker. Subsequent clicks should hide the date picker. <div class="col-xs-3"> <input id="datepick ...

Having trouble with my React input field - once I set the value, it becomes immutable

After setting the value of my state component, my React input component becomes uneditable state = {text: ''} return( <input id="search" type="text" value={this.s ...

Unlock the power of jQuery chaining with the val() method

My selected background color is set to: var _back = "#FF0000"; Why doesn't this code change the input field's background color: $("#input").val( _back ).css("background-color",$(this).val()); But this one does? $("#input").val( _back ) ...

jQuery fails to fetch information

I am currently working with a straightforward script as shown below: $(function() { var url = theme_directory + '/func/api.php'; $.get( url, function(data) { alert("Data Loaded: " + data); }); }); Here is the code for api ...

Having trouble getting images to display in Vue markdown?

I am currently utilizing the vue-markdown package for rendering markdown content. The package works fine except for images, which do not display as expected. Interestingly, when using an img element with the correct file path, the image shows up without an ...

Adjustable <a> component

There is this element: <a id="lnkViewEventDetails" class="psevdo calendar-event event" style="height: 126px;" href="/someurl/895?responseType=5" onclick="event.stopPropagation();"> I am trying to make it resizable using JQuery UI: $("#lnkViewEvent ...

No data found in Node.js after receiving AngularJS POST request

I've been working on sending a straightforward POST request to my server using AngularJS. The request successfully goes through and reaches the controller on the backend, but strangely, req.data is appearing as undefined. Front End Controller: funct ...

What is the best method to divide a string, enclose it within a span tag, and generate fresh code using jQuery?

Is there a way to separate multiple links, enclose them in a span tag, and then iterate through them to display them back within the a tag? I have managed to split all the dates into the dateArr array, but I need help looping through them to output each on ...

Utilizing AJAX to invoke a function

I'm having trouble explaining this, but I'll try my best. I created a function that calculates the remaining amount needed to qualify for free delivery based on different basket value thresholds. Whenever a product is added to the basket, the b ...

Searching with Sequelize for an indirect relationship: How can it be done?

Within my database, there exists a relationship between Users and Roles. A User can have multiple Roles assigned to them. These Roles are connected to Activities in such a way that they can be associated with many different activities. This association all ...

Implementing multiple modules within a shared parent route in Angular

Currently, I am seeking a method to load multiple modules under the same path in Angular. Let's say I have three modules: AModule, BModule, and CModule, each with its own RouterModule.forChild call. My goal is to combine these modules under the route ...

Adjust the current jQuery code to update the URL as the user scrolls

I have a jQuery code from w3schools.com that changes the URL's #id and enables smooth scrolling to a specific DIV section when clicking an <a href="#id"></a>. However, it does not work on scroll. I am looking for a solution where the URL&a ...

Can you explain the mechanics behind the animation of the upvote button on steemit.com?

Behold the upvote button of steemit.com: <span class="Icon chevron-up-circle" style="display: inline-block; width: 1.12rem; height: 1.12rem;"> <svg enable-background="new 0 0 33 33" version="1.1" viewBox="0 0 33 33" xml:space="preserve" xmlns=" ...