Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue js for non SPA apps - loading components in with out the app component

I am very new to Vue.js and I am trying to figure out a few things about it. One of the things I would like to use it for is to implement components without creating an SPA. So in other words I can make a reference to components in a static page with out having to have it run through App component.

When I have done this with react js I have used react habitat. I am wondering if there is something similar for Vue.js that is available or is it something you can do with out a third party module-tool.

like image 901
John williams Avatar asked May 16 '19 09:05

John williams


Video Answer


2 Answers

You don't need any App component. Just assign any wrapper (div) to a Vue module (Vue instance). I use a component for retrieving contacts, for example.

You can have multiple Vue applications in one page. They just cannot overlap.

html:

<div class="col-md-4 col-sm-4" id="safeContactsFooter">
 ..some html stuff

     <ul class="phone">
         <li>Phone: <safe-contact type="phone" ></safe-contact></li> 
     </ul>

</div>

Vue module:

export default new Vue({
    el: '#safeContactsFooter',

    components : {
        'safe-contact' : () => import('./components/Safe contact') ,
    },

});

Then, you have to register the module only when the div with the proper ID is present. Otherwise, the console will yell at you that the object doesn't exist. I do it this way:

if(document.getElementById("safeContactsFooter")){
    import('../Safe contacts/Safe contacts footer.Module.js');
}
like image 137
Peter Matisko Avatar answered Oct 14 '22 02:10

Peter Matisko


You can do that by importing your components into a JavaScript file and creating a vue instance with a referenced element:

// JS File
import Vue from 'vue';

import YourComponent from './YourComponent.vue';

export default new Vue({
   el: '#app',
   components: { 
     YourComponent
   }
});


// HTML file
<div id="app">
  <your-component></your-component>
</div>
like image 45
Kris D. J. Avatar answered Oct 14 '22 03:10

Kris D. J.