Navigation Using Router
First install the official vue-router package.
$ npm install --save vue-router
Create a new file ./src/app/router/index.js
and define a router as shown below.
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
export default new Router({
mode: 'history',
routes: [
{path: '/', component: require('../components/home.vue')},
{path: '/foo', component: require('../components/foo.vue')},
{path: '/bar', component: require('../components/bar.vue')},
{path: '*', redirect: '/'} // 404
],
scrollBehavior (to, from, savedPosition) {
return !savedPosition ? { x: 0, y: 0 } : savedPosition
}
});
Create components which we've defined in the router file above.
<template>
<div>./src/app/components/home.vue</div>
</template>
<template>
<div>./src/app/components/foo.vue</div>
</template>
<template>
<div>./src/app/components/bar.vue</div>
</template>
Open the ./src/app/components/app.vue
file and replace the existing template with the one below.
<template>
<div id="app">
<ul>
<li><router-link to="/">Home</router-link></li>
<li><router-link to="/foo">Foo</router-link></li>
<li><router-link to="/bar">Bar</router-link></li>
</ul>
<router-view class="view"></router-view>
</div>
</template>
Open the ./src/app/index.js
file and install the router.
...
import router from './router';
export const app = new Vue({
router,
...App
});
Open the ./src/app/server-entry.js
file and set router root path.
export default (ctx) => {
app.$router.push(ctx.url);
...
};
Open the ./src/server/router/routes/app.js
file and set application context as show below.
exports.render = (req, res) => {
let ctx = {url: req.originalUrl};
let page = req.vue.renderToStream(ctx);
...
}