DeployU
Interviews / Frontend Engineering / How do you do routing in Vue?

How do you do routing in Vue?

practical Routing Interactive Quiz Code Examples

The Scenario

You are a frontend engineer at a social media company. You are building a new single-page application (SPA) that will have multiple pages, such as a home page, a profile page, and a settings page.

You need to find a way to handle the routing between these pages.

The Challenge

Explain how you would do routing in Vue. What is Vue Router, and what are the key features of it?

Wrong Approach

A junior engineer might try to solve this problem by using a series of `v-if` statements to show and hide the different pages. This would not be a very scalable or maintainable solution.

Right Approach

A senior engineer would know that Vue Router is the perfect tool for this job. They would be able to explain what Vue Router is and how to use it to handle the routing between the different pages.

Step 1: Understand What Vue Router Is

Vue Router is the official router for Vue.js. It allows you to map URLs to components, so that you can build a single-page application with multiple pages.

Step 2: The Key Features of Vue Router

FeatureDescription
Nested RoutesYou can nest routes inside other routes to create complex layouts.
Dynamic RoutesYou can use dynamic segments in your routes to match a pattern, such as /user/:id.
Navigation GuardsYou can use navigation guards to protect routes from unauthorized access.
Lazy LoadingYou can lazy load routes to improve the performance of your application.

Step 3: Set Up Vue Router

Here’s how we can set up Vue Router in our application:

1. Install Vue Router:

npm install vue-router

2. Create a router instance:

import Vue from 'vue';
import VueRouter from 'vue-router';
import Home from './views/Home.vue';
import Profile from './views/Profile.vue';
import Settings from './views/Settings.vue';

Vue.use(VueRouter);

const routes = [
  { path: '/', component: Home },
  { path: '/profile', component: Profile },
  { path: '/settings', component: Settings }
];

const router = new VueRouter({
  routes
});

3. Add the router to the Vue instance:

new Vue({
  router,
  render: h => h(App)
}).$mount('#app');

4. Add the <router-view> component to your template:

The <router-view> component is where the component for the current route will be rendered.

<template>
  <div id="app">
    <router-view></router-view>
  </div>
</template>

Practice Question

You want to protect a route so that it can only be accessed by authenticated users. Which of the following would you use?