简体   繁体   中英

Migrating Js plugins to Vue

So I have a PHP app that renders some HTML, to provide interactivity on the site we had some js plugins that would be instantiated using some selectors and do their job (generate forms, load videos, etc).

Now I am trying to move those plugins to Vue 3 but I have some issues on getting the right approach.

My initial approach was to register my components and mount a single vue instance on a parent that would wrap around all the content on my site (Including statically generated HTML + my new vue components). But this approach didn't work because vue will just remove everything inside that wrapper.

The only way I was able to make my components work alongside my static HTML was by adding a wrapper element around my component and mounting a new Vue instance for each component I have on the page like so:

<div data-vue-component="">
   <foo-component/>
</div>

Is there a way to avoid doing this? Ideally, I would prefer only having a single instance on the page and just using the components alongside my static HTML.

So... This is really not an issue at all.

The easy fix was to provide the el: '#selector' property when creating the instance and removing the $mount('#selector') call.

So my code became

Vue.component('test-button', () => import('../vue-components/TestButton'))
Vue.component('test-component', () => import('../vue-components/TestComponent'))

const instance = new Vue({
   el: '.wrap'
})

And now I am able to use the 2 test components without having to create a new instance for each component.

Since I don't know if a page has a plugin or not, I've created a class to lazy load Vue using dynamic imports:

export class VueInitializer {
   static init () {
    const vueComponents = document.querySelector('[data-vue-component]')

    if (!vueComponents) {
        return
    }

    const vue = () => import('vue')


    vue().then((module) => {
        const Vue = module.default

        //lazy load la all components
        Vue.component('test-button', () => import('../vue-components/TestButton'))
        Vue.component('test-component', () => import('../vue-components/TestComponent'))
        const instance = new Vue({
            el: '.wrap'
        })
    })
}

}

The bad part of this implementation is that you will need to add a data attribute to our components.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM