Skip to content

Vue Router – thêm Route vào Router như thế nào

Table of Contents

    Như này

    const routes = [
      { path: '/', component: Home },
      { path: '/about', component: About },
    ]
    
    const router = VueRouter.createRouter({
      history: VueRouter.createWebHashHistory(),
      routes,
    })
    
    hoặc 
    router.addRoutes(routes)

    3 dạng Record

    • Single view record : có 1 component
    • Multiple view record : nhiều component
    • Redirect record : không có component

    Những object mà ta truyền vào trong routes sẽ là [RouteRecord] type
    • path : String
    • redirect : RouteLocationRaw
    { name: 'users', params: { username: 'posva' }, hash: '#bio' }
    • children : RouteRecordRaw – dùng nested view
    {
        path: '/user/:id',
        component: User,
        children: [
          {
            path: 'profile',
            component: UserProfile,
          },
        ],
      }
    • alias : String | String[]
    alias: '/home'
    
    alias: ['/people', 'list']
    • name : String
    • beforeEnter : NavigationGuard
    beforeEnter: (to, from) => {
          // reject the navigation
          return false
    }
    • props : boolean | v.v
    { component: User, props: true }
    
    {
        components: { default: User, sidebar: Sidebar },
        props: { default: true, sidebar: false }
    }
    
    // Truyền prop qua route
    props: { newsletterPopup: false }
    
    // function
    props: route => ({ query: route.query.q })
    • meta
    meta: { requiresAuth: true }
    • components

    Dynamic Route

    Là cách truyền thao số vào đường dẫn

    /users/:username/posts/:postId/users/eduardo/posts/123{ username: 'eduardo', postId: '123' }

    Watch Params Changes

    const User = {
      template: '...',
      created() {
        this.$watch(
          () => this.$route.params,
          (toParams, previousParams) => {
            // react to route changes...
          }
        )
      },
    }

    hoặc

    const User = {
      template: '...',
      async beforeRouteUpdate(to, from) {
        // react to route changes...
        this.userData = await fetchUser(to.params.id)
      },
    }

    Nested Route

    <div class="user">
          <h2>User {{ $route.params.id }}</h2>
          <router-view></router-view>
    </div>
    const routes = [
      {
        path: '/user/:id',
        component: User,
        children: [
          {
            path: 'profile',
            component: UserProfile,
          },
          {
            path: 'posts',
            component: UserPosts,
          },
        ],
      },
    ]

    /user/:id/profile is matched => <router-view/> là UserProfile

    /user/:id/posts is matched => <router-view/> là UserPosts

    {
        path: '/user/:id',
        component: User,
        children: [
          { path: '', component: UserHome },
        ],
    }

    /user/:id is matched => <router-view/> là UserHome (vẫn được render)

    Named Views

    dùng để phân chia thiên hạ

    <router-view class="view left-sidebar" name="LeftSidebar"></router-view>
    <router-view class="view main-content"></router-view>
    <router-view class="view right-sidebar" name="RightSidebar"></router-view>
    const router = createRouter({
      history: createWebHashHistory(),
      routes: [
        {
          path: '/',
          components: {
            default: Home,
            LeftSidebar,
            RightSidebar,
          },
        },
      ],
    })

    Redirect

    const routes = [{ path: '/home', redirect: { name: 'homepage' } }]
    const routes = [
      {
        path: '/search/:searchText',
        redirect: to => {
          return { path: '/search', query: { q: to.params.searchText } }
        },
      }
    ]

    Alias

    Thay vì redirect thì dùng alias nếu muốn nhiều “path” cùng chung route hãy sử dụng alias

    { path: '/', component: Homepage, alias: '/home' }
    
    path: '/users',
    children: [
    // - /users
    // - /users/list
    // - /people
    { path: '', component: UserList, alias: ['/people', 'list'] }
    
    path: '/users/:id',
    children: [
    // this will render the UserDetails for these 3 URLs
    // - /users/24
    // - /users/24/profile
    // - /24
    { path: 'profile', component: UserDetails, alias: ['/:id', ''] }

    Truyền Prop qua route

    • Boolean mode : cho phép route.params as props
    • Object mode : truyền object
    • Function mode : truyền function

    const User = {
      props: ['id'],
      template: '<div>User {{ id }}</div>'
    }
    const routes = [{ path: '/user/:id', component: User, props: true }]
    
    //===========================
    
    function dynamicPropsFn (route) {
      const now = new Date()
      return {
        name: (now.getFullYear() + parseInt(route.params.years)) + '!'
      }
    }
    
    const router = new VueRouter({
      mode: 'history',
      routes: [
        { path: '/path', component: Hello, props: { name: 'world' }}, // object
    
        { path: '/dynamic/:years', component: Hello, props: dynamicPropsFn }
      ]
    })

    Prop Named Views

    const routes = [
      {
        path: '/user/:id',
        components: { default: User, sidebar: Sidebar },
        props: { default: true, sidebar: false }
      }
    ]
    Published inVue Router

    Be First to Comment

    Leave a Reply

    Your email address will not be published. Required fields are marked *