Cómo usar un plugin de jQuery dentro de Vue


Estoy construyendo una aplicación web dentro de VueJS pero me encuentro con un problema. Quiero usar una extensión jQuery (cropit para ser específico) pero no se como instanciar/requerir/importarla de la manera correcta sin obtener errores.

Estoy usando la herramienta oficial CLI y la plantilla webpack para mi Aplicación.

Incluí jQuery así en mi página principal.archivo js:

import jQuery from 'jQuery'
window.jQuery = jQuery

Ahora estoy construyendo un componente de editor de imágenes donde quiero crear una instancia de crept como esta:

export default {
  ready () {
    $(document).ready(function ($) {
      $('#image-cropper-wrapper-element').cropit({ /* options */ })
    })
  },
 }

Pero Yo sigue recibiendo errores...Ahora mi pregunta es cómo crear una instancia adecuada de jQuery y plugins a través de NPM / Webpack / Vue?

Gracias de antemano!

Author: Luuk Van Dongen, 2016-06-20

5 answers

Opción # 1: Usar ProvidePlugin

Agregue el ProvidePlugin a la matriz de complementos tanto en build/webpack.dev.conf.js como en build/webpack.prod.conf.js para que jQuery esté disponible globalmente para todos sus módulos:

plugins: [

  // ...

  new webpack.ProvidePlugin({
    $: 'jquery',
    jquery: 'jquery',
    'window.jQuery': 'jquery',
    jQuery: 'jquery'
  })
]

Opción # 2: Usar el módulo Expose Loader para webpack

Como @TremendusApps sugiere en su respuesta, agregue el paquete Expose Loader:

npm install expose-loader --save-dev

Use en su punto de entrada main.js así:

import 'expose?$!expose?jQuery!jquery'

// ...
 48
Author: prograhammer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-18 00:32:07

Debe usar el cargador globals o el cargador expose para asegurarse de que webpack incluya la lib de jQuery en la salida del código fuente y para que no genere errores cuando use $ en sus componentes.

// example with expose loader:
npm i --save-dev expose-loader

// somewhere, import (require) this jquery, but pipe it through the expose loader
require('expose?$!expose?jQuery!jquery')

Si lo prefiere, puede importarlo (requerirlo) directamente dentro de su configuración de webpack como punto de entrada, así que lo entiendo, pero no tengo un ejemplo de esto a mano

Alternativamente, puede usar el cargador globals de esta manera: https://www.npmjs.com/package/globals-loader

 6
Author: Tremendus Apps,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-20 18:13:04

Lo uso así:

import jQuery from 'jQuery'

ready: function() {
    var self = this;
    jQuery(window).resize(function () {
      self.$refs.thisherechart.drawChart();
    })
  },
 2
Author: lukpep,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-21 06:46:09

Primero instale jquery usando npm,

npm install jquery --save

Utilizo:

global.jQuery = require('jquery');
var $ = global.jQuery;
widows.$ = $;
 2
Author: Rafael Andrs Cspedes Basterio,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-16 04:02:59

Supongamos que tiene un proyecto Vue creado con vue-cli (por ejemplo, vue init webpack my-project). Ir a project dir y ejecutar

npm install jquery --save-dev

Abra el archivo build/webpack.base.conf.js y agregue plugins:

module.exports = {
  plugins: [
    new webpack.ProvidePlugin({
      $: 'jquery',
      jquery: 'jquery',
      'window.jQuery': 'jquery',
      jQuery: 'jquery'
    })
  ]
  ...
}

También en la parte superior del archivo agregue:

const webpack = require('webpack')

Si está utilizando ESLint, abra .eslintrc.js y agregue las siguientes globales: {

module.exports = {
  globals: {
    "$": true,
    "jQuery": true
  },
  ...

Ahora estás listo para ir. Use anywhere en cualquier lugar de su js.

NOTA No es necesario incluir expose loader o cualquier otro personal para usar este.

originario de https://maketips.net/tip/223/how-to-include-jquery-into-vuejs

 1
Author: SkuraZZ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-29 09:27:16