vue-router 基础篇 笔记

97 阅读2分钟

写在开头

学习笔记,看完一遍,码一篇文章强化记忆

router.vuejs.org/zh/introduc…

html & javascript

<router-link to=''> link </router-link>
<router-view></router-view>
// 1. 定义路由组件.
// 也可以从其他文件导入
const Home = { template: '<div>Home</div>' }
const About = { template: '<div>About</div>' }

// 2. 定义一些路由
// 每个路由都需要映射到一个组件。
// 我们后面再讨论嵌套路由。
const routes = [
  { path: '/', component: Home },
  { path: '/about', component: About },
]

// 3. 创建路由实例并传递 `routes` 配置
// 你可以在这里输入更多的配置,但我们在这里
// 暂时保持简单
const router = VueRouter.createRouter({
  // 4. 内部提供了 history 模式的实现。为了简单起见,我们在这里使用 hash 模式。
  history: VueRouter.createWebHashHistory(),
  routes, // `routes: routes` 的缩写
})

// 5. 创建并挂载根实例
const app = Vue.createApp({})
//确保 _use_ 路由实例使
//整个应用支持路由。
app.use(router)

app.mount('#app')

// 现在,应用已经启动了!

动态配置路由

const router = {
    path: '/user/:id',
    component: User
}
// user
<template>
    <div>{{$router.params.id}}</div>
</template>

值得注意的几点

  • 路由可以被watch 监听
  • 有不同的传值方式和不用的取值方式 path, name --- params , name --- query name 形式的路由会在刷新页面时丢失参数,但这种路由的参数不会显示在url中

捕获所有的路由或者404 路由

const routes = [
  // 将匹配所有内容并将其放在 `$route.params.pathMatch` 下
  { path: '/:pathMatch(.*)*', name: 'NotFound', component: NotFound },
  // 将匹配以 `/user-` 开头的所有内容,并将其放在 `$route.params.afterUser` 下
  { path: '/user-:afterUser(.*)', component: UserGeneric },
]

路由嵌套

const routes = [
  {
    path: '/user/:id',
    component: User,
    children: [
      {
        ///user/:id/profile 匹配成功
        // UserProfile 将被渲染到 User<router-view> 内部
        path: 'profile',
        component: UserProfile,
      },
      {
        ///user/:id/posts 匹配成功
        // UserPosts 将被渲染到 User<router-view> 内部
        path: 'posts',
        component: UserPosts,
      },
    ],
  },
]

编程式导航

  • router.push
  • router.replace
  • router.go 三个api 对应history.pushState, replaceState, go

路由命名

路由视图

一个页面如果需要多个路由视图,可以给router-view 添加name 并在router中配置对应的组件, 如果组件仍需要使用子组件等嵌套路由组件,可以在

<router-view to='' name=''></router-view> 
<!-- UserSettings.vue -->
<div>
<h1>User Settings</h1>
<NavBar />
<router-view />
<router-view name="helper" />
</div>
{
  path: '/settings',
  // 你也可以在顶级路由就配置命名视图
  component: UserSettings,
  children: [{
    path: 'emails',
    component: UserEmailsSubscriptions
  }, {
    path: 'profile',
    components: {
      default: UserProfile,
      helper: UserProfilePreview
    }
  }]
}

重定向和别名

路由传参解耦

  • 布尔值
const User = {
  props: ['id'],
  template: '<div>User {{ id }}</div>'
}
const routes = [{ path: '/user/:id', component: User, props: true }]
  • 命名模式
const routes = [
  {
    path: '/user/:id',
    components: { default: User, sidebar: Sidebar },
    props: { default: true, sidebar: false }
  }
]
  • 对象模式
const routes = [
  {
    path: '/promotion/from-newsletter',
    component: Promotion,
    props: { newsletterPopup: false }
  }
]
  • 函数模式
const routes = [
  {
    path: '/search',
    component: SearchUser,
    props: route => ({ query: route.query.q })
  }
]