[英]How to solve “jQuery requires a window with a document” error?
在Nuxt.js,我在導入jQuery時遇到了一些問題。
我找到了一些我可以在Nuxt.js上使用jQuery的代碼
head: {
//other codes...
script: [
{
src: 'http://code.jquery.com/jquery-latest.min.js'
}
]}
如果我插入它,'$未定義'錯誤發生。
我也試過這個:
vendor: ['jquery', 'bootstrap'],
plugins: [
// set shortcuts as global for bootstrap
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery'
})
],
它工作,但'jQuery需要一個帶文檔的窗口'錯誤出現。
這是我的代碼:
//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>
我怎樣才能解決這個問題,並在Nuxt.js中使用jQuery?
由於Nuxt也在服務器上呈現,因此您無法使用依賴於窗口的JS,因為在服務器上呈現它不可用。
將您的jQuery腳本放入mounted()掛鈎。 請查看本指南https://www.encode8.com/js/guide-to-integrate-jquery-in-nuxt查看示例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.