How to set up routing in a Vue application?
Jul 30, 2025 am 02:33 AMInstall Vue Router: Use npm install vue-router@4 to install the corresponding version for the Vue 3 project. 2. Define routes: Configure the mapping of paths and components in src/router/index.js. 3. Integrated routing: Mount the route to the application instance in main.js through createApp(App).use(router). 4. Add navigation and exit: Use <router-link> to navigate in App.vue, and use
Setting up routing in a Vue application is essential when building single-page applications (SPAs) with multiple views. Here's how to do it step by step using Vue Router , the official routing library for Vue.

? 1. Install Vue Router
First, make sure you have a Vue project (using Vue 3 is recommended). Then install vue-router
via npm or yarn:
npm install vue-router@4
Note: For Vue 3, use Vue Router v4. If you're using Vue 2, install
vue-router@3
.
? 2. Define Your Routes
Create a router
directory in your project (eg, src/router/
) and add an index.js
file:
// src/router/index.js import { createRouter, createWebHistory } from 'vue-router' import HomeView from '../views/HomeView.vue' import AboutView from '../views/AboutView.vue' const routes = [ { path: '/', component: HomeView }, { path: '/about', component: AboutView } ] const router = createRouter({ history: createWebHistory(), routes }) export default router
Make sure the components (like
HomeView.vue
,AboutView.vue
) exist in thesrc/views/
folder or adjust the paths accordingly.
? 3. Integrate Router into Your App
Import and use the router in your main application file ( main.js
or main.ts
):
// src/main.js import { createApp } from 'vue' import App from './App.vue' import router from './router' createApp(App).use(router).mount('#app')
This connects the router to your Vue app instance.
? 4. Add Navigation and Route Outlet
In your App.vue
, use <router-link>
for navigation and <router-view />
as the outlet where routed components are rendered:
<!-- App.vue --> <template> <nav> <router-link to="/">Home</router-link> <router-link to="/about">About</router-link> </nav> <router-view /> </template> <style> /* Active link styling */ .router-link-exact-active { font-weight: bold; color: blue; } </style>
Now clicking on the links will change the view without a page reload.
? Extra Tips
- Dynamic Routes : Use params like
/user/:id
in your route path and access them viauseRoute()
composable. - Nested Routes : Define
children
in route config for nested UIs. - Lazy Loading : Improve performance by code-splitting:
const routes = [ { path: '/about', component: () => import('../views/AboutView.vue') } ]
- Route Guards : Use
beforeEach
for authentication checks:
router.beforeEach((to, from, next) => { if (to.path === '/secret' && !isAuthenticated) { next('/') } else { next() } })
That's it! You now have a working routing setup in your Vue app. With Vue Router, you can scale from simple navigation to complex route logic.
The above is the detailed content of How to set up routing in a Vue application?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

In Laravel, routing is the entry point of the application that defines the response logic when a client requests a specific URI. The route maps the URL to the corresponding processing code, which usually contains HTTP methods, URIs, and actions (closures or controller methods). 1. Basic structure of route definition: bind requests using Route::verb('/uri',action); 2. Supports multiple HTTP verbs such as GET, POST, PUT, etc.; 3. Dynamic parameters can be defined through {param} and data can be passed; 4. Routes can be named to generate URLs or redirects; 5. Use grouping functions to uniformly add prefixes, middleware and other sharing settings; 6. Routing files are divided into web.php, ap according to their purpose

ReactivitytransforminVue3aimedtosimplifyhandlingreactivedatabyautomaticallytrackingandmanagingreactivitywithoutrequiringmanualref()or.valueusage.Itsoughttoreduceboilerplateandimprovecodereadabilitybytreatingvariableslikeletandconstasautomaticallyreac

InternationalizationandlocalizationinVueappsareprimarilyhandledusingtheVueI18nplugin.1.Installvue-i18nvianpmoryarn.2.CreatelocaleJSONfiles(e.g.,en.json,es.json)fortranslationmessages.3.Setupthei18ninstanceinmain.jswithlocaleconfigurationandmessagefil

Server-siderendering(SSR)inVueimprovesperformanceandSEObygeneratingHTMLontheserver.1.TheserverrunsVueappcodeandgeneratesHTMLbasedonthecurrentroute.2.ThatHTMLissenttothebrowserimmediately.3.Vuehydratesthepage,attachingeventlistenerstomakeitinteractive

The steps to create a basic route in Laravel are as follows: 1. Open the route file located in routes/web.php; 2. Define the route using methods such as Route::get(), such as Route::get('/hello',function(){return'Hello,Laravel!';}); 3. Run the server through phpartisanserve and access http://localhost:8000/hello for testing; 4. Use Artisan to generate a controller such as HelloController and add processing methods there; 5. Update the route to point to the controller method, such as

ToaddtransitionsandanimationsinVue,usebuilt-incomponentslikeand,applyCSSclasses,leveragetransitionhooksforcontrol,andoptimizeperformance.1.WrapelementswithandapplyCSStransitionclasseslikev-enter-activeforbasicfadeorslideeffects.2.Useforanimatingdynam

nextTick is used in Vue to execute code after DOM update. When the data changes, Vue will not update the DOM immediately, but will put it in the queue and process it in the next event loop "tick". Therefore, if you need to access or operate the updated DOM, nextTick should be used; common scenarios include: accessing the updated DOM content, collaborating with third-party libraries that rely on the DOM state, and calculating based on the element size; its usage includes calling this.$nextTick as a component method, using it alone after import, and combining async/await; precautions include: avoiding excessive use, in most cases, no manual triggering is required, and a nextTick can capture multiple updates at a time.

Managing environment variables in Vue applications requires specific rules and using .env files. First, only variables prefixed with VUE_APP_ will be exposed to the application; second, different environments correspond to different .env files, such as .env.development, .env.production, etc.; third, variables are injected during construction and cannot be changed at runtime. The specific steps include: 1. Create .env files in the project root directory; 2. Use the corresponding .env files according to the pattern, such as .env.staging; 3. Access variables through process.env in the code; 4. You can import the variables into config.js for unified management; 5. If you need multiple environments to support, you can use package
