Vue3의 라우팅에 대해 이야기하고 라우팅 구성 방법을 간략하게 분석해 보겠습니다.

青灯夜游
풀어 주다: 2021-12-21 10:35:02
앞으로
3725명이 탐색했습니다.

이 글에서는 Vue3의 라우팅을 안내하고 라우팅의 기본 구성, 동적 라우팅 구성, 라우팅 모드, 라우팅 리디렉션 등에 대해 설명합니다. 도움이 되길 바랍니다.

Vue3의 라우팅에 대해 이야기하고 라우팅 구성 방법을 간략하게 분석해 보겠습니다.

【관련 추천: "vue.js tutorial"】

라우팅 기본 구성

1.routers.ts 파일을 생성합니다

3. .ts 구성요소를 소개하고 경로를 구성합니다.

npm install vue-router@next --save
로그인 후 복사

4. 라우팅 파일을 main.ts의 vue에 마운트합니다.

import { createRouter,createWebHashHistory } from 'vue-router';
// 引入组件
import Home from './components/Home.vue';
import News from './components/News.vue';
import User from './components/User.vue';

const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {path: '/', component: Home},
    {path: '/news', component: News},
    {path: '/user', component: User},
  ]
})

export default router;
로그인 후 복사

5. 라우팅을 사용하는 컴포넌트가 router-view 컴포넌트나 router-link

import { createApp } from 'vue'
import App from './App.vue'
import routers from './routers';

// createApp(App).mount('#app')

const app = createApp(App);
app.use(routers);
app.mount('#app');
로그인 후 복사

를 통해 router-link를 마운트한 후 해당 컴포넌트에 해당하는 페이지 경로에 지정된 경로만 입력하면 점프가 완료됩니다. Router-link는 레이블 점프 형태로 라우팅을 구현합니다.

동적 라우팅 구성

routes.ts에서 다음과 같이 라우팅을 구성하고, /:aid를 통해 동적 라우팅을 구성합니다.

<template>
  <img alt="Vue logo" src="./assets/logo.png">
  <ul>
    <li>
      <router-link to="/">首页</router-link>
    </li>
    <li>
      <router-link to="/news">新闻</router-link>
    </li>
    <li>
      <router-link to="/user">用户</router-link>
    </li>
  </ul>

  <router-view></router-view>
</template>
로그인 후 복사

라우터 링크를 통해 점프할 때 템플릿 문자열과 콜론 + to가 필요합니다.

//配置路由
const router = createRouter({

    history: createWebHashHistory(),
    routes: [
        { path: &#39;/&#39;, component: Home , alias: &#39;/home&#39; },
        { path: &#39;/news&#39;, component: News },
        { path: &#39;/user&#39;, component: User },
        { path: &#39;/newscontent/:aid&#39;, component: NewsContent },
    ], 
})
로그인 후 복사

this.$route.params를 통해 동적 경로가 전달한 값을 가져옵니다.

<ul>
    <li v-for="(item, index) in list" :key="index">
        <router-link  :to="`/newscontent/${index}`"> {{item}}</router-link>
    </li>
</ul>
로그인 후 복사

GET과 유사한 값 전송을 구현하려면 다음 방법을 사용할 수 있습니다.

1 경로를 일반 경로로 구성합니다.
mounted(){
    // this.$route.params 获取动态路由的传值
    console.log(this.$route.params)
}
로그인 후 복사

2. 라우터 링크가 물음표 형태로 점프합니다.

const router = createRouter({

    history: createWebHashHistory(),
    routes: [
        { path: &#39;/&#39;, component: Home , alias: &#39;/home&#39; },
        { path: &#39;/news&#39;, component: News },
        { path: &#39;/user&#39;, component: User },
        { path: &#39;/newscontent&#39;, component: NewsContent },
    ], 
})
로그인 후 복사

3. this.$route.query를 통해 get 값을 얻습니다.

<router-link  :to="`/newscontent?aid=${index}`"> {{item}}</router-link>
로그인 후 복사

경로 프로그래밍 방식 탐색(JS 점프 경로)

이것을 통해 지정하세요.$router.push.

console.log(this.$route.query);
로그인 후 복사

값 전송 가져오기를 구현하려면 다음 방법을 사용할 수 있습니다.

  this.$router.push({
    path: &#39;/home&#39;
  })
로그인 후 복사

동적 라우팅은 다음과 같은 방법을 사용해야 합니다.

this.$router.push({
    path: &#39;/home&#39;,
    query: {aid: 14}
  })
}
로그인 후 복사

라우팅 모드

해시 모드

해시 모드의 일반적인 특징은 페이지 경로에 파운드 기호가 포함되어 있다는 것입니다.

  this.$router.push({
    path: &#39;/home/123&#39;,
    // query: {aid: 14}
  })
로그인 후 복사

HTML5 기록 모드

    createWebHistory를 소개합니다.
  • 라우터 구성 항목의 기록 속성이 createWebHistory()로 설정되어 있습니다.
  • const router = createRouter({
    
        history: createWebHashHistory(),
        routes: [
            ...,
        ], 
    })
    로그인 후 복사
참고: HTML5 기록 모드를 켠 후 서버에 게시할 때 의사 정적을 구성해야 합니다.

의사 정적 구성 방법:

https://router.vuejs.org/zh/guide/essentials/history-mode.html#%E5%90%8E%E7%AB%AF%E9%85% 8D %E7%BD%AE%E4%BE%8B%E5%AD%90

이름이 지정된 경로

일반 상황

    경로를 정의할 때 이름 속성을 구성하세요
  • import { createRouter, createWebHistory } from &#39;vue-router&#39;
    
    //配置路由
    const router = createRouter({
        history: createWebHistory(),
        routes: [
            ...
        ], 
    })
    로그인 후 복사
    Incoming object Jump
  • { path: &#39;/news&#39;, component: News,name:"news" }
    로그인 후 복사
GET

    라우트 정의 시 name 속성을 설정하여 값을 전달
  • <router-link :to="{name: &#39;news&#39;}">新闻</router-link>
    로그인 후 복사
    쿼리를 포함한 객체에 전달
  • { path: &#39;/newscontent&#39;, component: NewsContent, name: "content" },
    로그인 후 복사
동적 라우팅을 통해 메소드

    는 동적 라우팅을 정의하고 이름 속성을 지정합니다.
  • <li v-for="(item, index) in list" :key="index">
        <router-link  :to="{name: &#39;content&#39;,query: {aid: index}}"> {{item}}</router-link>
    </li>
    로그인 후 복사
    매개변수를 포함한 객체에 전달
  • { path: &#39;/userinfo/:id&#39;, name: "userinfo", component: UserInfo }
    로그인 후 복사
프로그래밍 방식 라우팅

은 위의 방법과 매우 유사합니다.

<router-link :to="{name: &#39;userinfo&#39;,params: {id: 123}}">跳转到用户详情</router-link>
로그인 후 복사

경로 리디렉션
<button @click="this.$router.push({name: &#39;userinfo&#39;,params: {id: 666}})">点击跳转</button>
로그인 후 복사

경로 별칭

아래 예에서 사람 경로에 액세스하는 것은 별칭 경로에 액세스하는 것과 동일합니다.

{ path: &#39;&#39;, redirect: "/home" },   // 路由重定向
{ path: &#39;/home&#39;, component: Home },
로그인 후 복사

별칭도 배열일 수 있습니다.

{ path: &#39;/user&#39;, component: User, alias: &#39;/people&#39; }
로그인 후 복사

동적 라우팅 형태.

{ path: &#39;/user&#39;, component: User, alias: [&#39;/people&#39;,&#39;/u&#39;]}
로그인 후 복사

Nested Routing

Nested Routing의 적용 시나리오는 일반적으로 탐색 모음에 있습니다.

    중첩 라우팅 정의
  • { path: &#39;/userinfo/:id&#39;, name: "userinfo", component: UserInfo, alias: &#39;/u/:id&#39; }
    로그인 후 복사
    라우터 링크와 라우터 뷰가 협력하여 콘텐츠를 표시합니다.
  • {
      path: &#39;/user&#39;, component: User,
      children: [
        { path: &#39;&#39;, redirect: "/user/userlist" },
        { path: &#39;userlist&#39;, component: UserList },
        { path: &#39;useradd&#39;, component: UserAdd }
      ]
    }
    로그인 후 복사
    더 많은 프로그래밍 관련 지식을 보려면 프로그래밍 소개

    를 방문하세요! !

    위 내용은 Vue3의 라우팅에 대해 이야기하고 라우팅 구성 방법을 간략하게 분석해 보겠습니다.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:juejin.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!