How to quickly install, configure and use jQuery in vue3 project

  1. First, install jQuery using pnpm in the terminal or command line: (npm, yarn package managers can also be used)
    pnpm install jquery
    
  2. 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)
      }
    }
    
  3. Introduce this file in the main entry file (usually  main.ts) and  app.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')
    
  4.  Now you can access jQuery objects throughout your project via  $ : jQuery
  5. // 其他组件中
    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.

Guess you like

Origin blog.csdn.net/qq_62799214/article/details/132845614