[Vuejs]-Proper approach to showing subviews using Vue

1๐Ÿ‘

โœ…

Iโ€™ve never used angular but in Vue you can implement an SPA by using single file components and vue-router.

The approach is to have one page that serves all your components, and each component itself can be made up of multiple components. So firstly you set up a router like so:

// import top level components
import Foo from './foo.js'
import Bar from './bar.js'

// Define routes, each route serves up a component
const routes = [
  { path: '/foo', component: Foo },
  { path: '/bar', component: Bar }
]

// Create a router
const router = new VueRouter({
  routes
})

// Mount it to your div
const app = new Vue({
  router
}).$mount('#app')

In your HTML you then do:

<div id="app">
  <!-- links you registered earlier -->
  <p>
    <router-link to="/foo">Go to Foo</router-link>
    <router-link to="/bar">Go to Bar</router-link>
  </p>
   <!-- All content will be served up here -->
  <router-view></router-view>
</div>

Now vue will serve up Foo and Bar when those links are clicked.

As for serving up data, each component in a single file component is self contained, so you put the template, style and view model (data) relating to that component in one file:

<template>
  <div>
  {{message}}
  <my-component></my-component>
</div>

</template>

<script>
  // import components to be used in this component
  import myComponent from './myComponent'

  export default{
     // register imported components
     components: {
       myComponent
     },
     data(){
       return {
         message: 'Foo'
       }
     }
  }
</script>

These need to be compiled with something like webpack or browserify.

Essentially in the end you have a bunch of self contained components being served up by the router as the user navigates, and each component contains all the components it needs to function.

๐Ÿ‘คcraig_h

1๐Ÿ‘

Konrad,
I think you are looking for vue-router.
https://router.vuejs.org/en/

You have your navbar with <router-link>s
and then one <router-view> which will be replaced with appropriate component configured in routes

Your vapp is <router-view>.

Every view is separate VUE file (component).

It is the best to go with webpack-vue-template to develop more than simple component. If you want to have routing etc, you definitely should use webpack template.
https://github.com/vuejs-templates/webpack

Leave a comment