source

vue - 최신 하위 경로 제거

goodcode 2022. 7. 17. 00:26
반응형

vue - 최신 하위 경로 제거

라우터 패스는 현재 다음과 같이 설정되어 있습니다.

{
    component: List,
    name: "account-list",
    path: "list/:id",
    // alias: "list/:id/edit_item/:item_id",
    children: [
        {
            path: "edit_item/:item_id",
        },
        {
            path: "*",
            redirect: "/account/list/:id"
        }
    ]
}

예를 들어 다음과 같은 URL이 있다고 합시다.http://localhost:8080/#/account/list/5bb17bdec7fb946609ce8bd4/edit_item/5bbc2d12aded99b39c9eadb9

이걸 어떻게 바꿀 수 있을까요?

http://localhost:8080/#/account/list/5bb17bdec7fb946609ce8bd4

현재 사용하고 있습니다.

this.$router.back()

일반적으로는 잘 동작하지만, 만약 다른 아이템을 URL에 직접 붙여넣어 접속했다면,this.$router.back()이전 URL을 다시 방문합니다.

그럼 어린이 통로를 제거할 확실한 방법이 있을까요?

Vue 라우터는 네비게이션 시 현재 파라미터를 유지하므로 지정된 부모 루트로 네비게이트할 수 있습니다.

예를들면

this.$router.push({ name: 'account-list' })

현재:idparam이 재사용됩니다.

다이내믹하게 하고 싶다면 현재 루트를 따라갈 수 있습니다.matched예를 들어 현재 경로의 명명된 부모로 이동하려면

this.$router.push({
  name: this.$route.matched[this.$route.matched.length - 2].name 
})

이것은 물론 네스트된 루트에서만 동작합니다.matched최상위 루트의 길이는 1뿐입니다.


이름이 지정되지 않은 루트의 경우 문자열에 모든 파라미터가 삽입된 풀패스를 구축해야 합니다.행선지 루트를 취득하는 것으로, 그것을 실시할 수 있습니다.path속성과 파라미터 토큰의 치환this.$route.params하지만 그건 엉망진창이 될 거야

// get parent path property
let path = this.$route.matched[this.$route.matched.length - 2].path
let realPath = path.replace(/:\w+/g, param => 
    this.$route.params[param.substr(1)])
this.$router.push(realPath)

경로가 고급 패턴 매칭을 사용하는 경우 이 작업이 작동하지 않습니다.

자녀 루트를 한 단계 위로 이동시켜 아이가 더 이상 어린이가 되지 않도록 할 수 있습니다.그렇게 하면id에 나타나서this.$router.params물건.

[
  {
    path: 'list/:id',
    component: List,
    name: "account-list"
  },
  {
    path: 'list/:id/edit_item/:itemid',
    component: Form,
    name: "account-form"
  }
]

할 수 있다$router.replace현재 경로를 바꿉니다.

const id = this.$router.params['id'];

this.$router.replace({
  name: 'account-form',
  params: { id }
})

목록 ID 저장5bb17bdec7fb946609ce8bd4localStorage에서 해당 localStorage를 루트 스크립트 파일로 가져옵니다.리다이렉트 경로를 추가합니다.예:

var listId = localStorage.getItem('listId');
// routh obj
{
    component: List,
    name: "account-list",
    path: "list/:id",
    // alias: "list/:id/edit_item/:item_id",
    children: [
        {
            path: "edit_item/:item_id",
        },
        {
            path: "*",
            redirect: "/account/list/" + listId
        }
    ]
}

루트를 대체하기 전에 목록의 ID를 먼저 가져옵니다.

let currentId = this.$route.params.id
this.$router.replace({
  name: 'list',
  params: { id: currentId }
})

그리고 서브루트 이름을 붙이는 게 좋을 것 같아요

다음과 같이 할 수 있습니다.

window.history.slice(0,window.history.length);
this.$router.push(this.$route.path.split('/edit_item/')[0]);

언급URL : https://stackoverflow.com/questions/52713447/vue-remove-latest-child-path

반응형