对于大多数单页面应用,都推荐使用官方支持的vue-router库。更多细节可以看vue-router文档。
如果只需要非常简单的路由而不需要引入整个路由库,可以动态渲染一个页面级的组件像这样:
const notfound = { template: '<p>page not found</p>' }
const home = { template: '<p>home page</p>' }
const about = { template: '<p>about page</p>' }
const routes = {
'/': home,
'/about': about
}
new vue({
el: '#app',
data: {
currentroute: window.location.pathname
},
computed: {
viewcomponent () {
return routes[this.currentroute] || notfound
}
},
render (h) { return h(this.viewcomponent) }
})
结合html5 history api,你可以建立一个非常基本但功能齐全的客户端路由器。可以直接看实例应用。
如果有非常喜欢的第三方路由,如page.js或者 director, 整合很简单。 这有个用了page.js的复杂示例。