[Vuejs]-How to load external .js file in vue 2 component

0👍

If you have not already done so you need to use the webpack provide plugin to first include jQuery itself.

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

More here: https://webpack.js.org/plugins/provide-plugin/


I have always tried to avoid using jquery with vue, but one way I have used jquery on a very limited basis in a component is as follows.

Assume I have a very basic jquery plugin alertText.js defined as follows.

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

Then in my component.vue file I can include the jQuery plugin in much the same way as I would in any page.

<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>

Leave a comment