Vue Router Concept
vue's router is basically based on javascript's window.history (history API)
path is required name is optional
When you go to <route-link>or route.push
<router-view>
If you have registered a router object in your app like below, the following objects are available
this.$router // A router object needed to move the page (this.$router.push, etc.)
this.$route // An object with information about the current page (this.$route.params.id, etc.)
const router = useRouter() // Compositionapi
const route = useRoute() // Compositionapi
Register a router
const User = { template: '<div>foo</div>' }
const router = new VueRouter({
routes: [
{
path: '/user/:userId',
name: 'user', // Route with 1.name
component: User,
children: [ // 2.nested routes (i.e., child pages)
{ path: 'profile'
path: 'profile',
component: UserProfile // On matching /user/:id/profile, UserProfile will be rendered inside User's <router-view>.
meta: { requiresAuth: true } // 5. meta field, checked and available in the route's navguard (beforeEach), etc.
},
]
},
{
path: '/test',
components: {
default: Component2, // View with 3.name
a: Component2,
}
// If above, rendered below.
// <router-view ></router-view>
// <router-view name="a"></router-view> // <router-view name="a"></router-view>
},
{
path: '/a',
redirect: '/b', // 4. redirect can be to a path named /b or to a route with a specified name
//redirect: { name: 'foo' }
}
]
})
const app = new Vue({
router
}).$mount('#app')
Examples of using router
You can use either path or name
params are used with name
If you use params with path, enter them directly into the URL
All the examples below use the following URL
/user/123?plan=private
1. Declarative method
<router-link :to="{ name: 'user', params: { userId: 123 }, query: { plan: 'private' }}">nameuse</router-link>
<router-link :to="{ path: `/user/${userId}`, query: { plan: 'private' } }">pathUsing</router-link>
<router-link :to="/redirect" replace>
2.Programmatic
router.push({ name: 'user', params: { userId: 123 }, query: { plan: 'private' }})
router.push({ path: `/user/${userId}`, query: { plan: 'private' }})
router.push({ path: '/redirect', replace: true })
router.replace({ path: '/redirect' })
Router's functions and javascript's historyAPI comparison and explanation
router.push() === window.history.pushState()
Move to next page while building history (can go back)
router.replace() === window.history.replaceState()
Clears the past history and moves to the next page (can't go back)
router.go() === window.history.go()
Move forward or backward on the current page based on history
Passing objects between pages (using state)
How to send
router.push({
name: 'pate',
state: {
dataObj : { a:1, b:'string' },
},
});
How to get it
const { dataObj } = history.state
Reference