對于大多數(shù)單頁面應(yīng)用,都推薦使用官方支持的vue-router庫。更多細(xì)節(jié)可以看vue-router文檔。
如果只需要非常簡單的路由而不需要引入整個(gè)路由庫,可以動(dòng)態(tài)渲染一個(gè)頁面級的組件像這樣:
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) }
})
結(jié)合HTML5 History API,你可以建立一個(gè)非常基本但功能齊全的客戶端路由器。可以直接看實(shí)例應(yīng)用。
如果有非常喜歡的第三方路由,如Page.js或者 Director, 整合很簡單。 這有個(gè)用了Page.js的復(fù)雜示例。
更多建議: