Programing

Vue 1.x/2.x: $route 개체에서 vue-router 경로 URL 가져오기

c10106 2022. 5. 25. 20:27
반응형

Vue 1.x/2.x: $route 개체에서 vue-router 경로 URL 가져오기

우리가 알고 있듯이, 우리는vue-route길 좀 막아야겠어.

<!-- vue 1.x -->
<a v-link="{name: 'route_name', params: {id: 1}}"></a>

그리고 vue2의 경우:

<!-- vue 2.x -->
<router-link :to="{name: 'route_name', params: {id: 1}}"></router-link>

그리고 이제 사용자가 복사할 링크 URL을 표시하려고 하는데, 경로 객체에서 절대 경로 URL을 반환할 방법이 없을까?의사들이 그것에 대해 언급하지 않은 것 같았다.

예를 들어, 나는 다음을 원한다.

<template>
  <label>Copy the address</label>
  <input value="url" />
</template>

<script>
  export default {
    computed: {
      url() {
        const route = {name: 'route_name', params: {id: 1}};
        // !! The bellow shows what I may want.
        return this.$router.getLink(route);
      },
    }.
  };
</script>

그런 방법이 있을까?

이 일을 하려는 미래의 사람들을 위해

나는 이것이 Vue 2.x 길이라고 믿는다.

var path = this.$router.resolve({name: 'SomePath', params: {id: 1}}).href

만약 당신이 전체 URL을 원한다면 당신은

var fullUrl = window.location.origin + "/" + path

Vue 2.0에서는 내 방식을 시도해 볼 수 있다.this.$route.path도메인 없이 URL 경로를 가져올 수 있다.예를 들면 다음과 같다.http://localhost:8000/#/reg겨우 얻어먹다/regpart; vueRouter 밖에서 쉽게 얻을 수 있는 도메인 부분.BTW: 작성 후const router = new VueRouter ..., 를 사용하여 URL을 얻을 수 있다.router.history.current.path;이 방법은 다음과 같은 URL을 얻을 수 있다./reg나도 마찬가지야.

다음은 Vue#1.0 솔루션:

다음과 같은 경로 객체 전달:

const route = {name: 'route_name', params: {...}, query: {...}}

다음과 같은 방법으로:vm.$router.stringifyPathURL 경로를 반환하십시오.

그럼 그 경로를 이용해서hrefurl

그러나 라우터 시스템 모드가 무엇인지 알아야 하기 때문에,

export default {
  methods: {
    getUrlFromRoute(route) {
      const vm = this;
      let path = vm.$router.stringifyPath(route);
      if (vm.$router.mode === 'hash') {
        if (vm.$router.history.hashbang) {
          path = '!' + path;
        }
        path = '#' + path;
      }
      // finally we add the absolute prefix before that
      if (path[0] === '#') {
        // hash mode join
        path = location.origin + location.pathname 
             + (location.query||'') + path;
      } else if(path[0] === '/') {
        // absolute path
        path = location.origin + path;
      } else {
        // relative path
        path = location.origin + location.pathname.replace(/\/[^\/]+$/, '/') + path;
      }
      return path;
    }
  }
};

이제 우리는 다른 곳으로의 링크를 자유롭게 공유할 수 있다.

이전 답변이 삭제됨...

나는 https://github.com/vuejs/vuex-router-sync을 사용하고 그리고 필요한 부품에 사용한다.path나는 그것에 대한 재산을 계산해 보았다.간단하고 직진적인 솔루션.

일반적으로 진입점에서는main.js배치해야 하는 위치:

import { sync } from 'vuex-router-sync'
import store from './vuex/store' // vuex store instance
import router from './router' // vue-router instance

sync(store, router) // done.

필요한 구성 요소에서path당연히 그래야죠<script>:

computed: {
  path () {
    return store.state.router.path
  }
}

참조URL: https://stackoverflow.com/questions/41036009/vue-1-x-2-x-get-vue-router-path-url-from-a-route-object

반응형