5x0 精读Vue官方文档 - 路由

205 阅读1分钟

精读 Vue 官方文档系列 🎉

官方路由

推荐使用官方的路由库:vue-router

从零开始简单的路由

通过 H5 的 History API 结合 Vue 提供的动态组件技术实现一个非常简单的路由。

适用于你只需要非常简单的路由而不想引入一个功能完整的路由库。

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) }
})

整合第三方路由

上面的路由库用来学习研究或者结合 JQ 一起用于静态网页还是很合适的。