为什么不将 jQuery 与 Vue.js 一起用于 AJAX? [英] Why not use jQuery with Vue.js for AJAX?
问题描述
我正在尝试优化使用 Vue.js 的绿地项目的引用.它还使用 Bootstrap,需要 jQuery 来实现它的一些魔法,所以 jQuery 已经在混合中了.虽然我无意使用它的 DOM 操作工具,但 jQuery 已经存在了,所以有充分的理由不只是将它用于我的 Vue 组件中的 AJAX 调用吗?jQuery 和 axios 之间的语法非常相似,所以如果我可以避免添加另一个库,那就太好了.
I'm trying to optimize references on a greenfield project that uses Vue.js. It also uses Bootstrap, with requires jQuery for some of its magic, so jQuery is already in the mix. While I have no intention of using its DOM manipulation tools, jQuery is already there, so is there a good reason to not just use it for the AJAX calls from within my Vue components? The syntax between jQuery and axios is fairly similar, so if I can avoid adding another library, that would be groovy.
推荐答案
不要在 Vue 中使用 jQuery for AJAX"背后的原因口头禅是:
The reasons behind the "don't use jQuery for AJAX in Vue" mantra are:
- 如果
$
已经在组件中可用,则更倾向于查询或操作 DOM 而不是使用v-model
、v-if
、:class
等. - Axios 是一个出色的 AJAX 库,使用的数据比 jQuery 少.
- 使用 jQuery 可能导致难以维护 jQuery 插件和 Vue 组件之间的混合.
- If
$
is already available in the component, it's more tempting to query or manipulate the DOM instead of usingv-model
,v-if
,:class
, etc.. - Axios is an excellent library for AJAX and uses less data than jQuery.
- Using jQuery could lead to a hard to maintain mix between jQuery plugins and Vue components.
我的建议是编写一个简单的 api.js
帮助文件,其中包含以下方法:
My recommendation is to write a simple api.js
helper file with methods such as:
api.get(url)
api.post(url, data)
...etc.
这些方法可能会在内部使用 $.ajax
,但是当您升级到 Bootstrap 5 (不需要 jQuery),您可以将实现更改为其他内容.
These methods may use $.ajax
internally, but when you'll upgrade to Bootstrap 5 (which doesn't require jQuery) you can change the implementation to something else.
这篇关于为什么不将 jQuery 与 Vue.js 一起用于 AJAX?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!