2017-12-10 16 views
0

나는이 구성 요소참조하는 라우터 링크 PARAMS 데이터

<div class="card col-4" style="width: 22rem;"> 
 
    <img class="card-img-top" src="../assets/images/olu.jpg" alt="Card image cap"> 
 
    <div class="card-block"> 
 
    <h4 class="card-title">Card title</h4> 
 
    <p class="card-text">{{ stories.articles[0].summary }}</p> 
 
    <router-link :to="{path: '/viewArticle', params:{id:123}}"><a class="btn btn-primary">Continue Reading</a></router-link> 
 

 
    </div> 
 
</div>

공지 사항을 라우터 링크 태그가 ro

<template> 
 
    <div> 
 
    <div class="container row"> 
 
     <h1 class="display-3 col">Article in view</h1> 
 

 
    </div> 
 

 
    <div class="container"> 
 
     <img src="../assets/images/olu.jpg"/> 
 
     <article> 
 
     some text 
 
     </article> 
 

 
    </div> 
 

 
    </div> 
 

 

 
</template> 
 

 
<script> 
 
    // /console.log(params.id); 
 
    export default { 
 
    name: 'article', 
 
    data() { 
 
     return { 
 

 
     } 
 
    } 
 
    } 
 
</script>

이 절대적으로 잘 작동 아래 도시 된 article.vue 성분을 표시하는 uted. 내 질문은 위의 첫 번째 구성 요소에서와 같이/viewArticle 경로에 도달 할 때마다 반환되는이 article.vue 구성 요소 내부의 router-link params 속성에 전달 된 id 값을 참조하는 방법은 매우 간단합니다.

설명서와 기사를 살펴 보았지만 지금까지는 적절한 해결책을 찾을 수 없었습니다.

종류는 Passing Props to Router Component section에 설명 된대로

답변

2

당신은 문서 노선에 trueprops 속성을 설정할 수 있습니다 간주한다. 직접 구성 요소에

<script> 
    export default { 
    name: 'article', 
    props: ['id'], 
    data() { 
     return { 
     } 
    } 
    } 
</script> 

id 당신에게 사용할 수 있습니다 당신은 기사를 가져올 수 :

{ 
    name: 'article' 
    path: '/viewArticle/:id', 
    component: ArticleView // whatever you named the component 
    props: true 
} 

그런 다음 당신은 당신의 ArticleView 구성 요소 당신은 id 소품을 추가 할 수 있습니다.

id 대신 실제 기사가 전달되도록 기사를 미리로드 할 수도 있습니다. 라우터를 입력하기 전에

<script> 
    export default { 
    name: 'article', 
    props: ['id'], 
    data() { 
     return { 
     article: null, 
     } 
    }, 
    beforeRouteEnter (to, from, next) { 
     // your ajax stuff goes here 
     // I use axios in this example 
     axios.get(`/api/article/${to.params.id}`) 
     .then((article) => { 
      next(vm => { 
      vm.article = article 
      }) 
     }) 
     .catch(() => { 
      next('/404') 
     }) 
    } 
    } 
</script> 

가 그래서 기사를 가져옵니다 :

당신은 구성 요소에 beforeRouteEnter을 추가하여 그렇게. 이렇게하면 모든 구성 요소 코드에서 기사를 이미로드했다고 가정 할 수 있다는 장점이 있습니다. 로드되거나로드되지 않는 경우를 처리 할 필요가 없습니다.

또한 this.$route과 같은 탐색 경로와 this.$router (끝 부분에 r이 있음)과 같은 탐색 용 라우터에 액세스 할 수 있습니다.

+1

감사합니다. 서식 파일 본문에서 $ props.id를 사용하여 참조했습니다. – MGS

+0

템플릿 본문에 'id'만 사용할 수 있습니다. – Michael

+0

본문 {{id}}에서 이와 같이 참조하려했으나하지 않았습니다. 작업 – MGS