Vue Use Router

Posted on  by admin

Where to go from here

Modified3 years, 7 months ago. I'm learning Vue, and started of with the webpack template. The first thing I'm trying to do is to add support for Vue Router, but I've spent several hours on it now without being able to render a single route (I always end up with a blank page).

I simply want to have a single .vue file, acting as the layout file, into which different .vue files, acting as "pages", are rendered into.

Can someone tell me how to do this, please? Here's my latest failed attempt:. App.vue (the layout file). components/About.vue (almost identical to components/Home.vue).

JavaScript #

11 gold badge2424 silver badges4646 bronze badges. 4646 bronze badges. I finally got it to work. The main.js file should be written like this:.

I hope this saves hours of trouble for someone else. can preferably be replaced with:. 11 gold badge2424 silver badges4646 bronze badges.

4646 bronze badges. I found out how to get main.js to call the index.js file in folder router and work with the routes defined there: .

Handling 404 Not Found

I had created my app via the VUE UI (with VUE 3.1 and CLI/3) . In the VUE UI there is an option to add plugins.

  • I chose the router plugin (route) and it asked if I want to install a new route or install the framework.
  • (You first need to install the framework..) .
  • It then changed my main.js file to have the following: (the additions are marked with comments).
  • It also added a new folder router and in it index.js with the code.

It also installed the latest router package and added a link in the HelloWorld component to the router documentation.

By the way, notice the extra name: in the route definitions.

Starting From Scratch

33 gold badges3535 silver badges5858 bronze badges. 5858 bronze badges. Creating a Single-page Application with Vue + Vue Router feels natural: with Vue.js, we are already composing our application with components.

When adding Vue Router to the mix, all we need to do is map our components to the routes and let Vue Router know where to render them.

Here's a basic example:. Note how instead of using regular a tags, we use a custom component router-link to create links.

This allows Vue Router to change the URL without reloading the page, handle URL generation as well as its encoding.

We will see later how to benefit from these features. router-view will display the component that corresponds to the url. You can put it anywhere to adapt it to your layout. By calling app.use(router), we get access to it as this.$router as well as the current route as this.$route inside of any component:.

To access the router or the route inside the setup function, call the useRouter or useRoute functions.

We will learn more about this in the Composition API. Throughout the docs, we will often use the router instance.

Keep in mind that this.$router is exactly the same as directly using the router instance created through createRouter.

The reason we use this.$router is because we don't want to import the router in every single component that needs to manipulate routing.

How to use router params with Vue Router

If you’re looking to learn the new Vue Router that uses Vue 3, you’re in the right place. Many things are the same in Vue 3 using Vue Router, but there are a few small differences from Vue 2.

In this article, my aim is to give you an introduction to Vue Router for Vue 3, while highlighting the differences for those of you already familiar with the Router.

Vue is powerful for creating Single Page Applications: highly interactive webpages that don’t refresh when you change from page to page.

If your website has multiple pages (or “views”) and you’re using Vue, that’s why you need Vue Router.

I’m going to be building Vue 3 routing by starting with a basic Vue 3 app that I created using the Vue 3 CLI. Feel free to code along. From the command line I’ll need the most up-to-date CLI.

You can do this by running:. Then we’ll create our basic Vue 3 app. This will give us a screen where we’re going to choose to use “Vue 3 Preview”:.

This will create a base Vue 3 application, and we can ensure it works by going into the directory and running the server:.

Then when we go to [http://localhost:8080](http://localhost:8080) we should see our server running. To install Vue Router into our base Vue 3 project (as we created above) or into an existing project that already uses Vue 3, we’ll follow the steps below:.

Install the Vue 3 Router from the Command Line. Add a routing directory & configuration file. Notice that we create our routes in an array, where we specify for each route a few important items:.

Path - the URL path where this route can be found. Name - An optional name to use when we link to this route. Component - Which component to load when this route is called.

Below this array you’ll notice we create the Router itself, using the routes and we also pass in createWebHistory.

This is used to switch from using hash to history mode inside your browser, using the HTML5 history API. The way we configure this is a little different then we did in Vue 2.

How to access route params from the view

Notice we export this at the bottom because we’ll need to import it in our main.js file.

Importing our Routes & using Vue Router. Next we’ll need to edit our main.js file to use our router in our application.

Here we’re importing our router file, and then we use the router when creating our application.

The way our application is created in this file has changed in Vue 3.

Using and . There are two directives our Vue application gives us to use in our template:.

- When a route is navigated to in the browser, this is where the component is rendered.

For example, in our code going to / will render the Home component where we list .

- This is the directive we use to create links between our different component pages, instead of using .

These both can be used in our simple example in App.vue like so: (FYI, I erased what was already in the App.vue).

We’ll need to create our Home and About components which we referenced above.

Instead of putting them in our /components/ directory, I’m going to create a new /views directory. They’re going to be really simple for our example:. And now if we fire up our server and head up to [http://localhost:8080](http://localhost:8080) we should see the following:.

Much of the above configuration and setup you can actually have Vue 3 do for you from the CLI, but it’s valuable to know how to do it on your own.

If we wanted to use route names instead of paths, we could write our router-links like so:. Now our navigation works the same as before, but we’re not using paths. This can be useful if our URL paths change in the future.

We wouldn’t have to change all the router-links if the path changes, since they’re referencing using name. If we want to create a path URL which has a variable, like /user/gregg or event/5 where the ‘gregg’ or ‘5’ can be any name or any number, we need a Dynamic Segment. This is done JUST like we used to do it in Vue 2.

In the router, we specify in our route with the : denoting the variable.

(Don’t forget to import the User view in our route if you’re following along). To access that dynamic segment in the view itself, we could now write:.

And sure enough we get:. Also just like Vue 2, I can opt to have the dynamic segment passed into my component as a prop, but specifying props = true.

Named Routes

Now inside my component, I can have:. Notice I have to specify that my component is expecting a prop.

I get the same result:. Since we have a single page application, you’ll notice that if we go to any URL that doesn’t have a route mapped in the routing file we get an incomplete page. It loads up our App.vue, but no component.

We’ll need to tell our router what to do when it doesn’t match any routes, and the way we do this is a little different in Vue 3. We’ll need a route at the bottom of our routing list that looks like this:.

(If you’re coding along don’t forget to import the NotFound component at the top of your file.).

Notice the dynamic segment and the regular expression. :catchAll is the dynamic segment and (.*) is a regular expression, which essentially matches against anything. So if none of the routes above this one match, it will use this one. Also, I’ve imported a new component called NotFound which looks like this:.

Vue Router Fundamentals

Now when I try to go to http://localhost:8080/asdf, I get:. If you weren’t familiar with Vue Routing before, hopefully this gives you an idea just how easy it is to get going. If you are familiar, hopefully this comforts you to see there’s not a whole lot of differences between Vue 2 and Vue 3.

To learn more about the differences between the Vue 2 and Vue 3 router, check out the readme on the Vue 3 Router library. To continue learning Vue Router, you may want to take a read through the Vue 2 documentation.

As I showed you here, much of the syntax is the same. One of the most powerful features of modern single-page web applications (SPA) is routing.

Modern single-page apps such as a Vue application can transition from page to page on the client-side (without requesting the server). Vue Router is the official library for page navigation in Vue applications. Vue Router is simple to use, yet powerful. In this article, we will deep dive into Vue Router 4 (used with Vue 3).

We will go over everything you need to know to use Vue Router comfortably. Vue Router Fundamentals .

Dynamic routing . How to pass router params.

Whether you are a beginner just getting into Vue Router or a seasoned JavaScript/Vue developer looking to skill up, there’s something for you in this tutorial.

Let’s get started. 👉 We have also created a completely free in-depth Vue Router video course. If you learn better by watching videos, we highly recommend you give it a shot.

Dynamic Segments

Click here to watch the Vue Router course. Let’s create a new project and get right into coding. We’ll create a new project with vue-cli.

If you don’t have it installed you can install it by running npm install -g @vue/cli. Next we can add the Vue Router to our project by running the following command. The cli will ask if we want history mode.

For this tutorial we’ll be using history mode, so we’ll select yes. Let’s take a look at the folder structure that was created for us.

Not the answer you're looking for? Browse other questions tagged vue.jsvue-router or ask your own question.

A folder named views is created for us along with two files About.vue and Home.vue. These files represent our pages. A file named router/index.js file is also generated.

This file contains all the router configurations. Let’s open up the router/index.js file. We are importing createRouter and createWebHistory from the vue-router library.


Next, we import the Home component from views/Home.vue. On line 3 we are declaring an array of objects named routes. This array represents our routes in the application.

These array items are called route objects. The first route object has a path / which means this is going to be our base URL. The component property represents what component will be rendered when the user visits this path.

We will render the Home page on this path. Finally, the name property represents the name of the route.

We are pretty much following the same logic for the /about the path. However, instead of directly importing the component we are importing it through Webpack’s code splitting feature.

More on this later. Now let’s jump into App.vue file. Observe the router-link tags. These tags are just fancy anchor links. However unlike an anchor link ( tag) the will not reload the whole page.

Remember Vue is a single-page application. The data for the app is already downloaded from the server. When we route to another view the application just hides some information and displays the requested information.

router-link tags have a to property which refers to which page to visit. The tag is what renders the right component when navigation links are triggered.

Installing from the CLI

Let’s add our own route to this application. We need to add a new router-link to App.vue. Next we create a new component in the views directory. Finally, in our routes array we have to import this and specify the route path.

That’s it we have our own routes added to the application. First of all, let’s take a look at what router parameters (router params in short) are and why they are important.

Let’s say we have a page in our application where we show users a list of all the blog posts available. Let’s say in our application this path is /posts. When a user clicks on any of these articles the user is taken to that article page. For each article the path will be different (/posts/article-1, /posts/article-2, etc.).

Why Vue Router?

How do we achieve this? We can add a new route for every post we have, but then we have to change our code every time a new post is published.

Therefore, we will use a dynamic route. This is where router params comes in handy. In our application, we can specify a generic route like the /posts and, then we can specify optional route params to the same route like this /posts/:id.

The :id picks up any dynamic string as a parameter. This means we can now route to paths like /posts/article-1 , /posts/article-2, etc. and the Vue router in the application will know which path we are trying to go to.

Let’s see this in action inside our application. In our router-link tag we can use the :to property to pass in an object with name and params data. The params object can be any type of data (i.e. strings, numbers, objects).

In the code snippet above we are passing in an object with username with a string value (mark2021). When we add Vue router to our Vue application we get access to a special $route object inside the global scope of our application. This object holds all the router information of our application. We can access $route object by simply calling this.$route.

The params information is also available within this $route object. We can access the params object inside of the Profile component through the $route object.

Take a look at the code snippet below.

Dynamic Routing

Below is a quick reference table to help you visualize how dynamic routes work. In the previous section we saw how, we can pass in additional information with . Dynamic routes are a similar concept. In this scenario the parameter is a part of the URL itself.

Let’s take a look how we can define dynamic routes in our application.

Let’s create a new component under view and call it Product.

Programmatic Navigation

Debugging Vue.js applications can be difficult, especially when there are dozens, if not hundreds of mutations during a user session. If you’re interested in monitoring and tracking Vue mutations for all of your users in production, try LogRocket.

LogRocket is like a DVR for web and mobile apps, recording literally everything that happens in your Vue apps including network requests, JavaScript errors, performance problems, and much more. Instead of guessing why problems happen, you can aggregate and report on what state your application was in when an issue occurred.

The LogRocket Vuex plugin logs Vuex mutations to the LogRocket console, giving you context around what led to an error, and what state the application was in when an issue occurred.

Modernize how you debug your Vue apps - Start monitoring for free.