Nuxt.js: It's not clear how to include jQuery code

Created on 7 Mar 2017  Â·  22Comments  Â·  Source: nuxt/nuxt.js

I can't find anything in the docs about how to include snippets of JS or local JS files, that contain jQuery (I have jQuery itself included from a CDN). Whatever I have tried has resulted in errors ranging from $ is not defined to jQuery requires a window with a document. Any pointers?

This question is available on Nuxt.js community (#c308)
help-wanted

Most helpful comment

I use jQuery code in this way

<template>
<!-- Body -->
</template>

<script>
import $ from 'jquery'

export default {
  mounted: () => {
    // jQuery code
  }
}

</script>

All 22 comments

Take a look at the How to add webpack plugins.

Hi @awronski

Yeah, I tried that already, in combination with plugins: ['~assets/js/my-file.js'], but got the jQuery requires a window with a document error.

You need to check if you are executing your script in the browser:

if (process.BROWSER_BUILD) { ... }

OK, I think that's the part I'm missing. Which script? Could you elaborate.

You are writing some javascript code in which you want to use jquery. Right?
Then the code is executed twice, on the server-side during ssr and then
later in the browser.

In the ssr you don't have to window this is why you need to wrap your code
with the condition.

BTW, Why do you need jquery when you can do everything even easier without
it thanks to the vue directives?

On Wed, Mar 8, 2017 at 10:14 AM, Sam Smith notifications@github.com wrote:

OK, I think that's the part I'm missing. Which script? Could you elaborate.

—
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
https://github.com/nuxt/nuxt.js/issues/356#issuecomment-284988174, or mute
the thread
https://github.com/notifications/unsubscribe-auth/AB4d3e2Z_TOfdTvZ3_VfwZOJZLwRFVYKks5rjnGNgaJpZM4MWCRh
.

That's right.

I'm still not sure what to put into if (process.BROWSER_BUILD) { ... }.

I have tried

if (process.BROWSER_BUILD) {
   const webpack = require('webpack')
}

and

if (process.BROWSER_BUILD) {
   require('my-file')
}

and

if (process.BROWSER_BUILD) {
   const webpack = require('webpack')
   plugins: [
     '~assets/js/my-file.js'
   ]
}

None of which change the error.

I have also tried variations of

if (process.BROWSER_BUILD) {
   const webpack = require('webpack')
   plugins: [
     '~assets/js/my-file.js'
   ],
   build: {
     plugins: [
       new webpack.ProvidePlugin({
         '$': 'jquery'
       })
     ]
   }
}

which give a syntax error.

I'm not familiar enough with Vue directives to know how they can be a replacement for jQuery, but I essentially want to use it to add/remove classes.

From your snippet it looks like you want to manipulate DOM from the
external script in the browser.
But you are including jquery plugin to use it in the server generated code.

IMHO This does not make a sense.

About the styles, look at this:
https://vuejs.org/v2/guide/class-and-style.html

On Wed, Mar 8, 2017 at 10:41 AM, Sam Smith notifications@github.com wrote:

That's right.

I'm still not sure what to put into if (process.BROWSER_BUILD) { ... }.

I have tried

if (process.BROWSER_BUILD) {
const webpack = require('webpack')
}

and

if (process.BROWSER_BUILD) {
require('my-file')
}

and

if (process.BROWSER_BUILD) {
const webpack = require('webpack')
plugins: [
'~assets/js/my-file.js'
]
}

None of which change the error.

I have also tried variations of

if (process.BROWSER_BUILD) {
const webpack = require('webpack')
plugins: [
'~assets/js/my-file.js'
],
build: {
plugins: [
new webpack.ProvidePlugin({
'$': 'jquery'
})
]
}
}

which give a syntax error.

I'm not familiar enough with Vue directives to know how they can be a
replacement for jQuery, but I essentially want to use it to add/remove
classes.

—
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
https://github.com/nuxt/nuxt.js/issues/356#issuecomment-284994366, or mute
the thread
https://github.com/notifications/unsubscribe-auth/AB4d3WRO54_bhiKPRk_Ast3MpuqdmzC3ks5rjnfngaJpZM4MWCRh
.

OK, so how should I be including it?

you need to register jquery in the nuxt.config.js and of course install it
with npm.

Here are examples: https://github.com/nuxt/nuxt.js/issues/178

On Wed, Mar 8, 2017 at 10:53 AM, Sam Smith notifications@github.com wrote:

OK, so how should I be including it?

—
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
https://github.com/nuxt/nuxt.js/issues/356#issuecomment-284996880, or mute
the thread
https://github.com/notifications/unsubscribe-auth/AB4d3YeAyzrFahr0wDRfB4OBxPPz3bYOks5rjnqOgaJpZM4MWCRh
.

So you can't use jQuery from a CDN?

OK, so now I have

const webpack = require('webpack')

module.exports = {
plugins: [
    '~assets/js/my-file.js'
  ],
build: {
    vendor: ['jquery'],
    plugins: [
      new webpack.ProvidePlugin({
        '$': 'jquery'
      })
    ]
}

But this doesn't seem to move things forward. I still get the same jQuery requires a window with a document error. And I still have not got anything inside if (process.BROWSER_BUILD) {} in the template.

Hi, @smth!
did you try this?

in nuxt.config.js

plugins: [
   '~plugins/my-jquery-code.js'
]

in plugins/my-jquery-code.js

if (process.BROWSER_BUILD) {
   const $ = require('jquery')
   $(function() {
      console.log('document ready!');
      // do whatever you want with html and jquery
   })
}

Here is my scenario how I made jquery work with nuxt.
1) Install it from npm.
2) import it in component which requires it. Like import $ from 'jquery'
3) Call $ in all lifecycle hooks after created() and it works since document exists by that time. $ should also work in component methods.

P.S.
I tried using jquery to manipulate some classes and stuff in vue app, but it seems now that using vue and vuex features is more convenient. Most jquery usages can be refactored with help of store for global things and props if you need some data only locally in your components. Seems more vue-way for me.

I didn't @KonstantinVlasov, but that looks straight-forward and promising. I decided to go for a more Vue way, using directives for now. So I gave up on jQuery for the time being, but I'll probably revisit this at some point.

I use jQuery code in this way

<template>
<!-- Body -->
</template>

<script>
import $ from 'jquery'

export default {
  mounted: () => {
    // jQuery code
  }
}

</script>

@alexchopin i cant understand how fix this problem?

@smth I fixed that error by adding window as prefix ! No need webpack and npm !!!
just

window.$

Following NuxtJS guidelines. I think we are supposed to install jquery via npm ? And include it via vendor?

https://nuxtjs.org/guide/plugins/

It would be included in all pages. Correct?

You can add any external JS libraries in head option: https://nuxtjs.org/faq/

module.exports = {
head: {
script: [
{ src: 'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js' }
],
link: [
{ rel: 'stylesheet', href: 'https://fonts.googleapis.com/css?family=Roboto' }
]
}
}

Hi @awronski,

I have 10 dymanic form (see img). each form has (-) and (+) button with one text box. i want to increase and decrease when being click respective by button. I am able to achieve this by jquery easly (.parent.find...)

but i am really cluless how to do the same with properly vuejs style. i am using Nuxt.

image
Any help pls

@sudhir600 Hi sudhir, you can use data binding in vue js. Supposed you have the following component with button:

<template>
    <p>{{ amount }}</p>
    <a class="btn" href="#" v-on:click="increaseAmount()">Plus (+)</a>
    <a class="btn" href="#" v-on:click="decreaseAmount()">Minus (-)</a>
</template>

<script>
export default {
  data () {
    return {
      amount: 0
    }
  },
  methods: {
    increaseAmount () {
      this.amount = this.amount + 1
    },
    decreaseAmount () {
      this.amount = this.amount - 1
    }
  }
}
</script>

Then, you should render each product in those image to each different component. See Component Basics#BaseExample on vue.js guide.

unfortunately, this.amount is not affecting in the textbox. when i console.log, i get increment number but textbox doesn't (added v-model)

So finally i use plain javascript (document.getElemntById().....)

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

o-alexandrov picture o-alexandrov  Â·  3Comments

mikekidder picture mikekidder  Â·  3Comments

shyamchandranmec picture shyamchandranmec  Â·  3Comments

nassimbenkirane picture nassimbenkirane  Â·  3Comments

bimohxh picture bimohxh  Â·  3Comments