页面切换好夥伴- Vue Router [续]

Vue Router 设定

延续上次的设定档

// src/router/index.js
import { createWebHistory, createRouter } from "vue-router";
import Home from "@/views/Home.vue";
import About from "@/views/About.vue";

const routes = [
  {
    path: "/",
    name: "Home",
    component: Home,
  },
  {
    path: "/about",
    name: "About",
    component: About,
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

export default router;

使用阵列来建立我们的 routes,每一个 route 都有几项特别项目需要注意:

  • Path : 路由的 URL 路径
  • Name : link 到此路由的名称
  • Component : 当路由被呼叫时,要载入的元件

createRouter 中,除了传入 routes 外还可以传入 createWebHistory选择要使用 hash 或是 history mode。

接着就可以在main.js中加入 router

// src/main.js
import { createApp } from 'vue'
import App from './App.vue'
import router from './router' // <---加这 加这

createApp(App).use(router).mount('#app')

具名路由 (Named Routes)

指定 name 当作路由的参考

const router = new VueRouter({
  routes: [
    {
      path: '/user/:userId',
      name: 'user',
      component: User
    }
  ]
}

传入一个物件给 router-linkto 属性

<router-link :to="{ name: 'user', params: { userId: 123 }}">User</router-link>

对应的 URL 为 /user/123


转址 (redirect)

/a 转页到 /b

const router = new VueRouter({
  routes: [
    { path: '/a', redirect: '/b' }
  ]
})

也可以透过 name

const router = new VueRouter({
  routes: [
    { path: '/a', redirect: { name: 'foo' }}
  ]
})

别名 (alias)

和转址差异在於,转址是 URL 会被替换;而别名像是替路由再取另个名字,但网址列看到的 URL 不会被替换

const router = new VueRouter({
  routes: [
    { path: '/a', component: A, alias: '/b' }
  ]
})

 造访 /b 时,URL 保持 /b,但是匹配到 /a 的内容


参考

Vue Router: A Tutorial for Vue 3


下篇预告

  • Vuex

每日一句:
使用者访谈,原来痛点在这里 /images/emoticon/emoticon06.gif


<<:  DAY22 - 将作品发布出去吧 - 前端篇 (firebase)

>>:  Day22-JDK可视化监控工具:jconsole(二)

Day 17 UItableView的练习 (1/3)

上次做过调色盘的练习,对基本的东西有一些认识之後我们开始继续往下练习~ 其实TableViewy我们...

介绍一套 free syslog Visual Syslog Server for Windows 1.6.4

介绍一套 free syslog Visual Syslog Server for Windows ...

ISO 27001 资讯安全管理系统 【解析】(十二)

资通安全责任等级 依照资通安全责任等级分级办法,由主管机关核定相对应之等级,按照等级决定导入系统之...

Ascii - 产生 3D 旋转甜甜圈的甜甜圈形 C 程序码参考笔记

Ascii - 产生 3D 旋转甜甜圈的甜甜圈形 C 程序码参考笔记 参考资料 参考资料: Donu...

Day30 I’m on the next level

Summary 承续昨天所说,我们将PivotTable.js的版面调整,让资料区域的表格和图表可...