vuejs 教程,vue3.0 文档,vuejs 实战,前端框架,vuejs 入门,vue3.0 迁移,vue3资讯,Vue3最新动态,vuejs 中文社区,javascript中文网,vuejs 面试题,vuejs bug

# 路由

# 官方 Router

对于大多数单页面应用,都推荐使用官方支持的 vue-router 库 (opens new window)。更多细节可以移步 vue-router 文档 (opens new window)

# 从零开始简单的路由

如果你只需要非常简单的路由而不想引入一个功能完整的路由库,可以像这样动态渲染一个页面级的组件:

const NotFoundComponent = { template: '<p>Page not found</p>' }
const HomeComponent = { template: '<p>Home page</p>' }
const AboutComponent = { template: '<p>About page</p>' }

const routes = {
  '/': HomeComponent,
  '/about': AboutComponent
}

const SimpleRouter = {
  data: () => ({
    currentRoute: window.location.pathname
  }),

  computed: {
    CurrentComponent() {
      return routes[this.currentRoute] || NotFoundComponent
    }
  },

  render() {
    return Vue.h(this.CurrentComponent)
  }
}

Vue.createApp(SimpleRouter).mount('#app')
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

结合 HTML5 History API (opens new window),你可以建立一个麻雀虽小但是五脏俱全的客户端路由器。为了获得更多的实践,可以直接查看实例应用 (opens new window)

# 整合第三方路由

如果你有更加偏爱的第三方路由,如 Page.js (opens new window) 或者 Director (opens new window),整合起来也一样简单 (opens new window)。这里有一个使用了 Page.js 的完整示例 (opens new window)

Js中文网,专注分享前端最新技术、大厂面试题、聊点程序员轶事、职场感悟,做前端技术的传播者.

加入前端布道师交流群

扫描二维码回复 加群 学习,与大厂大佬讨论技术.