Vue.js基础教程(官方手册)
/ 路由
路由
本章节我们将为大家介绍 Vue.js 路由。Vue.js 路由允许我们通过不同的 URL 访问不同的内容。通过 Vue.js 可以实现多视图的单页Web应用(single page web application,SPA)。
目录
官方路由
对于大多数单页面应用,都推荐使用官方支持的 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 的完整示例。