route 데이터 사용법

6797 단어
vue-router 1 사용 방법https://github.com/vuejs/vue-router/tree/1.0/docs/zh-cn data(transition) [-> Promise] Called on an incoming component during the activation phase, after the activate hook has been resolved. It is also called when the route has changed and the current component is reused. Use this hook to load and set data on the current component.
활성화 단계 후 갈고리를 활성화하여 해결한 후 전송된 구성 요소에 호출합니다.루트가 변경되고 현재 구성 요소가 다시 사용될 때도 호출됩니다.이 갈고리를 사용하여 현재 구성 요소의 데이터를 불러오고 설정합니다.
Arguments • transition {Transition}Calling transition.next(data) will set each property in data on the component. For example, with { a: 1, b: 2 }, the router will call component.$set('a', 1) and component.$set('b', 2).
transition을 호출합니다.next (data) 는 구성 요소의 데이터에 모든 속성을 설정합니다.예를 들어 {a:1, b:2}를 사용하면 공유기는 구성 요소 $set('a', 1)과 구성 요소 $set('b', 2)을 호출합니다.
Expected Return Value • optionally return a Promise. ◦ resolve(data) -> transition.next(data) ◦ reject(reason) -> transition.abort(reason) ** • OR:** return an Object containing Promises. See Promise sugar below.
Details The data transition hook is called immediately after the activate hook is resolved, and right before the view switching is executed. The entering component gets a $loadingRouteData meta property, which starts with value true and set to false when the data hook is resolved. This property can be used to display a loading state for the entering component. When resolved, the component will also emit a 'route-data-loaded' event.
갈고리 해석을 활성화하면 데이터 변환 갈고리를 즉시 호출하고 보기 전환을 실행하기 전에 즉시 호출합니다.구성 요소에 들어가서 **$loadRouteData ** 요소 속성을 가져옵니다. 값은true로 시작하고 데이터 갈고리가 해석될 때false로 설정합니다.이 속성은 입력 구성 요소의 불러오는 상태를 표시하는 데 사용됩니다.해결 시 구성 요소는 '루트 데이터 불러오기' 이벤트를 보냅니다.
The data hook is different from activate in that:
  • data is also called every time the route changes, even if the current component is reused, while activate is only called when component is newly created. Imagine we have a component for the route/message/:id, and we are currently on/message/1. When the user navigates to/message/2, the current component can be reused, so the activate hook will not get called. But we do want to fetch and update the data based on the new id param, so in most cases it makes sense to do data fetching in data instead of activate.

  • 데이터 갈고리는 활성화와 다르다. 현재 구성 요소가 다시 사용되더라도 루트가 바뀔 때마다 데이터를 호출하고, 활성화는 구성 요소가 새로 만들어질 때만 호출됩니다.상상해 보세요. 우리는 루트/메시지/:id의 구성 요소가 있습니다. 우리는 현재/메시지/1에 있습니다.사용자가/메시지/2를 탐색할 때 현재 구성 요소를 다시 사용할 수 있기 때문에 활성화된 갈고리는 호출되지 않습니다.단, 우리는 새로운 id 파라미터를 바탕으로 데이터를 얻고 업데이트하기를 원하기 때문에, 대부분의 경우 활성화가 아닌 데이터로 데이터를 얻는 것이 의미가 있다.
    2.activate's responsibility is controlling the timing of switching to the new component. In comparison, data is called right after activate is resolved and right before the view switching happens, so the data fetching and the new component's entering animation will go in parallel, and the component will be in a "loading"state before data is resolved.
    활성화의 책임은 새 구성 요소로 전환하는 시간을 제어하는 것입니다.이에 비해 데이터는 활성화 해결 후 바로 호출됩니다. 보기 전환이 발생하기 전에 데이터 가져오기와 새 구성 요소의 입력 애니메이션이 병행되고 구성 요소는 데이터 분석 전에 '불러오기' 상태가 됩니다.Let's consider the difference in the User Experience here: • If we wait for the data to be fetched before displaying the new component, the user will feel like the interface is "stuck"for a split second before the view switches. •만약 우리가 새 구성 요소를 표시하기 전에 데이터를 얻기를 기다린다면, 보기 전환을 하기 전에 사용자는 인터페이스가 1초 동안 끊겼다고 느낄 것이다.Instead, we can react to user input instantly and start switching the view, while displaying the new component with a "loading"state. If we have a CSS transition in between, the animation time can overlap nicely with the data wait time. •반대로 우리는 사용자의 입력에 즉시 반응하고 보기를 전환하며 '불러오기' 상태로 새 구성 요소를 표시할 수 있습니다.만약 우리 사이에 CSS 변환이 있다면 애니메이션 시간은 데이터 대기 시간과 겹칠 수 있습니다.With that said, if you still wish to wait until data is loaded before switching the view, you can add waitForData: true inside your component's route option.
    Examples By calling transition.next:
    route: {
      data: function (transition) {
        setTimeout(function () {
          transition.next({
            message: 'data fetched!'
          })
        }, 1000)
      }
    }
    

    By returning a Promise:
    route: {
      data: function (transition) {
        return messageService
          .fetch(transition.to.params.messageId)
          .then(function (message) {
            return { message: message }
          })
      }
    }
    

    Parallel requests, with Promise & ES6:
    route: {
      data ({ to: { params: { userId }}}) {
        return Promise.all([
          userService.get(userId),
          postsService.getForUser(userId)
        ]).then(([user, post]) => ({ user, post }))
      }
    }
    

    Equivalent of above in ES5:
    route: {
      data (transition) {
        var userId = transition.to.params.userId
        return Promise.all([
          userService.get(userId),
          postsService.getForUser(userId)
        ]).then(function (data) {
          return {
            user: data[0],
            posts: data[1]
          }
        })
      }
    }
    

    Using $loadingRouteData in templates:
    Loading ...

    Promise Sugar The parallel data fetching example above requires us to leverage Promise.all to combine multiple Promises into a single one, and the desturcturing and formatting is still a bit cumbersome. vue-router provides a syntax sugar which allows you to return an Object containing Promises (it can contain non-Promise fields too, of course). 상기 병렬 데이터 획득 예시에서 우리는 Promise를 이용해야 한다.all는 여러 개의 Promises를 하나로 조합하고, desturcturing과 포맷은 여전히 좀 번거롭다.vue-router는 문법 설탕을 제공합니다.Promises를 포함하는 대상을 되돌려줍니다. (물론 비Promise 필드도 포함할 수 있습니다.)Here's the same example using the syntax sugar and ES6:
    route: {
      data: ({ to: { params: { userId }}}) => ({
        user: userService.get(userId),
        post: postsService.getForUser(userId)
      })
    }
    

    The router will set the component's user and post fields to the corresponding Promises' resolved values when they are resolved. $loadingRouteData will be set to false when all Promises have been resolved. Equivalent in ES5:
    route: {
      data: function (transition) {
        var userId = transition.to.params.userId
        return {
          user: userService.get(userId),
          post: postsService.getForUser(userId)
        }
      }
    }
    

    참조 사이트 주소:https://github.com/vuejs/vue-router/blob/1.0/docs/en/pipeline/data.md
    Contact GitHub API Training Shop Blog About

    좋은 웹페이지 즐겨찾기