目前,jQuery 3.1.4 正在由 CDN 在首页外部加载。
索引.vue
head: {
bodyAttrs: {
id: 'overview'
},
script: [
{
src: 'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js'
}
]
}
在下方页面中,由于 jQuery 插件,1.8.3 包含在 CDN 中。
**/index.vue
head: {
bodyAttrs: {
id: 'lower'
},
script: [
{
src: 'https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.min.js'
}
]
}
用jQuery创建的多个js放在assets目录下,模块化导入。还有一些其他的js文件。
ex)~/assets/useragent.js
/* global $ */
export default function () {
// User agent
var _ua = (function (u) {
return {
Tablet: (u.indexOf("windows") != -1 && u.indexOf("touch") != -1 && u.indexOf("tablet pc") == -1) || u.indexOf("ipad") != -1 || (u.indexOf("android") != -1 && u.indexOf("mobile") == -1) || (u.indexOf("firefox") != -1 && u.indexOf("tablet") != -1) || u.indexOf("kindle") != -1 || u.indexOf("silk") != -1 || u.indexOf("playbook") != -1,
Mobile: (u.indexOf("windows") != -1 && u.indexOf("phone") != -1) || u.indexOf("iphone") != -1 || u.indexOf("ipod") != -1 || (u.indexOf("android") != -1 && u.indexOf("mobile") != -1) || (u.indexOf("firefox") != -1 && u.indexOf("mobile") != -1) || u.indexOf("blackberry") != -1
}
})(window.navigator.userAgent.toLowerCase());
// Is in viewport
$.fn.isInViewport = function (screen) {
var elementTop = $(this).offset().top;
var elementBottom = elementTop + $(this).outerHeight();
var viewportTop = $(window).scrollTop();
var viewportBottom = (viewportTop + $(window).height()) * screen;
return elementBottom > viewportTop && elementTop < viewportBottom;
};
$(window).on('load resize scroll', function () {
$('.shuffle-item--visible').each(function () {
if ($(this).isInViewport(4)) {
$(this).addClass('in_viewport');
} else {
$(this).removeClass('in_viewport');
}
});
});
}
索引.vue
mounted: function() {
this.$nextTick(() => {
if (process.browser) {
JqueryEasing()
MagnificPopup()
useragent()
}
})
}
}
检查的时候,我补充说应该在nuxt.config.js中描述以下内容。
nuxt.config.js
build: {
plugins: [
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.$': 'jquery',
'window.jQuery': 'jquery'
})
]
}
当我运行 npm run dev 时,出现以下错误并且无法编译。
These dependencies were not found: friendly-errors 17:19:16
friendly-errors 17:19:16
* $ in ./assets/js/useragent.js friendly-errors 17:19:16
* jQuery in ./plugins/02_jquery.easing.1.3.min.js friendly-errors 17:19:16
friendly-errors 17:19:16
To install them, you can run: npm install --save $ jQuery
如何使用 CDN 编译单独的 jQuery 版本?
之后,我检查了它并将其设置为外部,这样它就不会在模块中读取
build: {
extend(config, ctx) {
config.externals = {
jquery: 'jQuery'
};
}
}
可以编译,但是页面是“Cannot find module 'jQuery' from '/~'”,看不到。