gpt4 book ai didi

javascript - 在 Vue 项目中包含或初始化 jQuery 库的最佳方法是什么?

转载 作者:搜寻专家 更新时间:2023-10-30 22:34:47 25 4
gpt4 key购买 nike

在 Vue 项目中包含 jQuery 库的最佳方式是什么?

我正在使用 vue-cli、webpack 和路由器。我有单独的组件,我需要包括几个 jQuery 插件。如果我在索引文件中包含 jQuery 脚本,那么我在从组件操作(触发)DOM 时就会遇到问题。所以我想最好将所有脚本包含在我的 main.js 或组件中?

我需要实现 Venobox插入。这是基本的 jQuery 初始化

$(document).ready(function(){
$('.venobox').venobox();
});

我在 Vue 中尝试过

  mounted () {
$('.venobox').venobox();
}

现在我遇到了 jQuery 的问题。 '$' 未定义等。在 Vue 项目中包含外部 JS 文件的最佳实践是什么?有没有简单的方法来初始化 jQuery 插件?

谢谢!

最佳答案

如果只有这个组件使用 jQuery,我会只在其中导入它,而不会为其他任何事情操心。您的代码是正确的(在 mounted 生命周期 Hook 中初始化 venobox),但您还必须在组件中导入 jQuery:

import $ from 'jquery';

export default {
mounted () {
$('.venobox').venobox();
}
}

但是,如果您也在其他组件中使用 jQuery,我建议您在这里查看这个答案 https://stackoverflow.com/a/39653758/2803743 .粘贴选项 1 以防它被删除/更改(使用 Webpack 的 ProvidePlugin):

Option #1: Use ProvidePlugin

Add the ProvidePlugin to the plugins array in both build/webpack.dev.conf.js and build/webpack.prod.conf.js so that jQuery becomes globally available to all your modules:

plugins: [
// ...

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

关于javascript - 在 Vue 项目中包含或初始化 jQuery 库的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44498053/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com