亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Table of Contents
? 1. Install Vue Router
? 2. Define Your Routes
? 3. Integrate Router into Your App
? 4. Add Navigation and Route Outlet
? Extra Tips
Home Web Front-end Vue.js How to set up routing in a Vue application?

How to set up routing in a Vue application?

Jul 30, 2025 am 02:33 AM
vue routing

Install 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 to display the corresponding components. Finally, it realizes refresh-free view switching for single-page applications, and fully supports advanced functions such as dynamic routing, nested routing, lazy loading and routing guarding.

How to set up routing in a Vue application?

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.

How to set up routing in a Vue application?

? 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 .

How to set up routing in a Vue application?

? 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 &#39;vue-router&#39;
import HomeView from &#39;../views/HomeView.vue&#39;
import AboutView from &#39;../views/AboutView.vue&#39;

const routes = [
  { path: &#39;/&#39;, component: HomeView },
  { path: &#39;/about&#39;, component: AboutView }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

export default router

Make sure the components (like HomeView.vue , AboutView.vue ) exist in the src/views/ folder or adjust the paths accordingly.

How to set up routing in a Vue application?

? 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 &#39;vue&#39;
import App from &#39;./App.vue&#39;
import router from &#39;./router&#39;

createApp(App).use(router).mount(&#39;#app&#39;)

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 via useRoute() composable.
  • Nested Routes : Define children in route config for nested UIs.
  • Lazy Loading : Improve performance by code-splitting:
 const routes = [
  { path: &#39;/about&#39;, component: () => import(&#39;../views/AboutView.vue&#39;) }
]
  • Route Guards : Use beforeEach for authentication checks:
 router.beforeEach((to, from, next) => {
  if (to.path === &#39;/secret&#39; && !isAuthenticated) {
    next(&#39;/&#39;)
  } 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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are routes in Laravel, and how are they defined? What are routes in Laravel, and how are they defined? Jun 12, 2025 pm 08:21 PM

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

What is the significance of Vue's reactivity transform (experimental, then removed) and its goals? What is the significance of Vue's reactivity transform (experimental, then removed) and its goals? Jun 20, 2025 am 01:01 AM

ReactivitytransforminVue3aimedtosimplifyhandlingreactivedatabyautomaticallytrackingandmanagingreactivitywithoutrequiringmanualref()or.valueusage.Itsoughttoreduceboilerplateandimprovecodereadabilitybytreatingvariableslikeletandconstasautomaticallyreac

How can internationalization (i18n) and localization (l10n) be implemented in a Vue application? How can internationalization (i18n) and localization (l10n) be implemented in a Vue application? Jun 20, 2025 am 01:00 AM

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

What is server side rendering SSR in Vue? What is server side rendering SSR in Vue? Jun 25, 2025 am 12:49 AM

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

How do I create a basic route in Laravel? How do I create a basic route in Laravel? Jun 19, 2025 am 01:03 AM

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

How to implement transitions and animations in Vue? How to implement transitions and animations in Vue? Jun 24, 2025 pm 02:17 PM

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

What is the purpose of the nextTick function in Vue, and when is it necessary? What is the purpose of the nextTick function in Vue, and when is it necessary? Jun 19, 2025 am 12:58 AM

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.

How can environment variables be managed and accessed within a Vue application? How can environment variables be managed and accessed within a Vue application? Jun 14, 2025 am 12:22 AM

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

See all articles