Reputation: 13
At Nuxt.js, I have some problems importing jQuery.
I found some code which I can use jQuery at Nuxt.js
head: {
//other codes...
script: [
{
src: 'http://code.jquery.com/jquery-latest.min.js'
}
]}
If I insert it, '$ is not defined' error occurred.
I already tried this, too:
vendor: ['jquery', 'bootstrap'],
plugins: [
// set shortcuts as global for bootstrap
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery'
})
],
it works, but 'jQuery requires a window with a document' error appears.
This is my code:
//nuxt.config.js
const webpack = require('webpack');
module.exports = {
/*
** Headers of the page
*/
head: {
title: 'nuxt_test_d',
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'description', name: 'description', content: 'Nuxt.js project' }
],
link: [
{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
],
script: [
{
src: 'http://code.jquery.com/jquery-latest.min.js'
}
]
},
/*
** Customize the progress bar color
*/
loading: { color: '#3B8070' },
/*
** Build configuration
*/
build: {
// vendor: ['jquery'],
/*
** Run ESLint on save
*/
vendor: ['jquery', 'bootstrap'],
plugins: [
// set shortcuts as global for bootstrap
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery'
})
],
extend (config, { isDev, isClient }) {
if (isDev && isClient) {
config.module.rules.push({
enforce: 'pre',
test: /\.(js|vue)$/,
loader: 'eslint-loader',
exclude: /(node_modules)/
})
}
}
}
}
//index.vue
<template>
<div class="id_pw_input_cover" id="id_pw_input_cover" style="width: 430px; height: 300px;">
<div class="id_cover input_cover fadeIn animated time_1_3s delay_0_5s">
<p class="input_info">ID</p>
<input type="text" id="id" class="id input_tag" name="id" onchange="login_id(this)"/>
</div>
<div class="pw_cover input_cover fadeIn animated time_2s delay_0_5s">
<p class="input_info">PW</p>
<input type="password" id="pw" class="pw input_tag" name="pw" onchange="login_pw(this)"/>
</div>
</div>
</template>
<script>
$('#id').change(function() {
if (id == "") {
$('#id').css('border-color', 'red');
}
if (pw == "") {
$('#pw').css('border-color', 'red');
}
if (id != "") {
$('#id').css('border-color', 'white');
}
if (pw != "") {
$('#pw').css('border-color', 'white');
}
});
</script>
How can I solve this problem, and use jQuery in Nuxt.js?
Upvotes: 0
Views: 2797
Reputation: 515
As Nuxt also renders on the Server you can't use JS that relies on window because on server render it's not available.
Put your jQuery scripts into the mounted() hook. Check this guide https://www.encode8.com/js/guide-to-integrate-jquery-in-nuxt to see a example.
Upvotes: 4