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

2

9

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.

Colcannon answered 16/5, 2019 at 9:17 Comment(0)
F
8

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');
}
Farro answered 16/5, 2019 at 9:24 Comment(0)
D
5

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>
Deadbeat answered 16/5, 2019 at 9:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.