Vue.js | Routing
Routing is one of the many features provided by Vue.js to allow users to switch between pages without refreshing every time a page is loaded. This results in smooth transitions between pages giving a better feel for the user.
Setting Up The Application: Firstly, we need to create a project to work on. We can use Vue CLI (Command Line Interface) for this. With the terminal open, run the following below command.
vue init webpack vue-routing-example
During the initialization process, make sure to say yes when prompted to install the vue-router. It is required in order to work with routing in our application. After the initialization is over, open up the application to check if the process was successful by running the following command in the terminal:
npm run dev
With those commands, your application would be built and deployed into the local development server.
Building Our Application: In order to implement routing in our application, we must first create pages to route to. We can change and use the HelloWorld.vue file as our first page and create a new file in that component folder HelloGeek.vue as our second page. These pages will have nothing functional and will be for understanding the flow of routing.
- Step 1: Replace the content of HelloWorld.vue with the below code. The template section is where we structure the visible content of the component. Here, it displays a parameter (msg) as a heading that is passed to it from the script section of the code. The script section is used to hold the logic of our code which in this case is to return a value.
- Step 2: Paste the below code into HelloGeek.vue file. Same as HelloWorld.vue for template and script section.
- Step 3: Now as we have our pages ready, we need to configure our index.js file in order to set up routing configuration.
- In the import section we have imported both Vue and Router to help build our project. We have also imported both the pages we want to route to – HelloWorld and HelloGeek.
- Vue.use(strong) is used to make sure that the Router is added as a helper in our project.
- Here, as a special case, the root path is redirected to HelloWorld page as the root should never be empty.
- Ste 4(Optional): The user can now manually route to each page by changing the URL to http://localhost:8080/#/helloworld or http://localhost:8080/#/hellogeek. But let us set up ways to route through links.
- Step 5: Here we will do Route Linking, we can set up links to routes using the <route-link> tag. The to attribute is to be given a path to the page we need to route.
<router-link to="/helloworld">Hello World</router-link>
- The template section contains an image followed by route links to our pages using the <router-link> tag.
- The <router-view> placeholder tag is used to define the place where the route component would be inserted into the HTML output.
- The style section of the code, well, helps styling the page.