Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple Vue Instances on same page using same codebase

I'm working on bringing the functionality of Vue.js, into the WordPress ecosystem, and my first project is for Search and Filtering on a page.

Because the main website is being rendered initially by WordPress with PHP/HTML, I have Vue initializing on the page attaching to an HTML element I output using WordPress. This all works perfectly fine, but now i'm trying to take this a step further by having multiple instances of the same codebase (that can work together)

Take this example screenshot from indeed (just assume this is a WordPress site): multiple vue instances

Because the entire output is not being done in Vue.js, I have to output multiple HTML DIV elements from the WordPress side, and initialize Vue on them.

Because the form/fields will be dynamically generated based on user configuration/setup, the same code base would be used for both instances ... but i somehow need to make it so they can work together in unison, to say, update the results on the page, when a value is selected or changed, in any of the instances.

The idea here is in my main JS file using vanilla javascript to detect all of my specific HTML elements that exist on the page (maybe even define a slug for each one in a data object), and then doing a foreach loop to then init a new Vue() on each instance.

My first thought is to use Vuex storage, attaching the single storage to all instances, storing any selected values, and triggering a dispatch to update the listings when any of them change.

Has anybody done anything similar to this before? Anything I should be weary about in doing this? Or anybody have any better suggestions on how this should be done?

Figured it would be better for me to ask on here instead of learning the hard way and then finding out later that it may not be possible, or that there will be issues in doing so.

Any suggestions, comments, criticisms, or ideas are greatly appreciated

update Had one suggestion to just bind the Vue instance to the body, remove the render function, and then just output the component HTML element where needed (instead of outputting a div then attaching to it). Going to test this out, but curious on thoughts surrounding this?

like image 751
sMyles Avatar asked Aug 29 '19 17:08

sMyles


1 Answers

For anybody that comes across this, I ended up just initializing the Vue instances like this:

const sections = document.getElementsByClassName( "my-wrapper" )

for ( var i = 0; i < sections.length; i ++ ) {
    new Vue( {
         el: '#' + sections[ i ].id,
         store
     })
}

Basically initializing new Vue instance on each output found on the page, passing the shared store to each one.

like image 193
sMyles Avatar answered Sep 20 '22 18:09

sMyles