- First, install jQuery using pnpm in the terminal or command line: (npm, yarn package managers can also be used)
pnpm install jquery
- Create a separate file in your Vue 3 project, for example
jquery.ts/jquery.js
, to import and globally register jQuery:import { App } from 'vue' import jQuery from 'jquery' export default { install: (app: App) => { app.config.globalProperties.$ = jQuery app.config.globalProperties.jQuery = jQuery app.provide('jQuery', jQuery) } }
- Introduce this file in the main entry file (usually
main.ts
) andapp.use()
register the jQuery plug-in using the method:import { createApp } from 'vue' import App from './App.vue' import jQueryPlugin from './jquery.ts' const app = createApp(App) app.use(jQueryPlugin) app.mount('#app')
- Now you can access jQuery objects throughout your project via
$
:jQuery
// 其他组件中 export default { mounted() { this.$('#myElement').addClass('highlight') } }
Please note that Vite no longer needs to configure the global ProvidePlugin like Vue CLI, and due to the different module resolution method of Vite, using it directly in Vue 3
import $ from 'jquery'
is not recommended.
How to quickly install, configure and use jQuery in vue3 project
Guess you like
Origin blog.csdn.net/qq_62799214/article/details/132845614
Recommended
Ranking