programing

Vue-Router가 데이터를 다른 컴포넌트로 전달

firstcheck 2022. 7. 3. 19:17
반응형

Vue-Router가 데이터를 다른 컴포넌트로 전달

Vue-Router를 사용하여 컴포넌트 간에 데이터를 전달하는 데 문제가 있습니다.

메인 컴포넌트에 다음 템플릿이 있습니다.

<li><router-link to="/">Daily</router-link></li>
<li><router-link to="/weekly/">Weekly</router-link></li>
<router-view></router-view>

그리고 내 안에DailyComponent컴포넌트에는 다음 데이터 기능이 있습니다.

data() {
  return {
    userCount: 0,
  }
}

두 번째 링크는 다음 컴포넌트로 전송됩니다.WeeklyComponent.

어떻게 패스하지?userCount: 0에서 얻은 데이터DailyComponent로.WeeklyComponent거기에 전시하는 건가요?

감사합니다!

이 질문은 컴포넌트 간에 데이터를 공유하는 방법으로 컴포넌트를 설계하는 방법에 관한 것입니다.이것을 하는 방법은 여러 가지가 있는데, 각각 상황에 따라 장단점이 있다.stackoverflow/google에 대해 자세히 설명했으므로 이 방법을 검색해 보는 것이 좋습니다.

의 소유자를 높이다userCount부모에 대한 데이터

상위 컴포넌트를 의 소유자로 합니다.userCount소품을 통해 하위 컴포넌트에 전달합니다.하위 구성 요소가 해당 데이터를 수정하려면 다음 작업을 수행해야 합니다.$emit부모가 응답하여 값을 업데이트할 수 있는 새 값을 가진 이벤트입니다.

const Daily = {
  props: ['userCount'],
  template: '<p>Daily: {{ userCount }} <button @click="increment">+ 1</button></p>',
  methods: {
    increment() {
      this.$emit('user-count', this.userCount + 1);
    }
  }
};

const Weekly = {
  props: ['userCount'],
  template: '<p>Weekly: {{ userCount }} <button @click="increment">+ 5</button></p>',
  methods: {
    increment() {
      this.$emit('user-count', this.userCount + 5);
    }
  }
};

new Vue({
  el: '#app',
  router: new VueRouter({
    routes: [
      { path: '/daily', component: Daily },
      { path: '/weekly', component: Weekly }
    ]
  }),
  data: {
    userCount: 0,
  },
})
<script src="https://rawgit.com/vuejs/vue/dev/dist/vue.js"></script>
<script src="https://rawgit.com/vuejs/vue-router/dev/dist/vue-router.js"></script>

<div id="app">
  <router-link to="/daily">Daily</router-link>
  <router-link to="/weekly">Weekly</router-link>
  
  <router-view :user-count="userCount" @user-count="userCount = $event"></router-view>
</div>

Vuex 또는 기타 외부 상태 관리

Vuex의 예는 이미 많기 때문에 여기서는 복제하지 않지만 원하는 상태 관리 시스템을 사용할 수 있습니다.

Vuex는 당신의 예에 대해 과잉일 수 있습니다.대신 공유된 반응형 개체를 전달할 수 있습니다.

const Daily = {
  props: ['shared'],
  template: '<p>Daily: {{ shared.userCount }} <button @click="increment">+ 1</button></p>',
  methods: {
    increment() {
      this.shared.userCount += 1;
    }
  }
};

const Weekly = {
  props: ['shared'],
  template: '<p>Weekly: {{ shared.userCount }} <button @click="increment">+ 5</button></p>',
  methods: {
    increment() {
      this.shared.userCount += 5;
    }
  }
};

new Vue({
  el: '#app',
  router: new VueRouter({
    routes: [
      { path: '/daily', component: Daily },
      { path: '/weekly', component: Weekly }
    ]
  }),
  data: {
    shared: {
      userCount: 0,
    }
  },
})
<script src="https://rawgit.com/vuejs/vue/dev/dist/vue.js"></script>
<script src="https://rawgit.com/vuejs/vue-router/dev/dist/vue-router.js"></script>

<div id="app">
  <router-link to="/daily">Daily</router-link>
  <router-link to="/weekly">Weekly</router-link>
  
  <router-view :shared="shared"></router-view>
</div>

Vuex글로벌 이벤트 버스 같은 것을 사용할 수 있습니다.두 구성 요소에 공통 상위 구성 요소를 가질 수도 있습니다.

이벤트 버스를 이용하면 앱 내 어디에서나 해당 값을 포함한 이벤트를 내보내고 들을 수 있습니다.공통의 부모 컴포넌트가 있는 경우,userCount두 개의 하위 구성요소에 소품으로 전달한 다음 하위 구성요소에서 부모에게 이벤트를 내보냅니다.자녀가 값을 변경할 때마다 이벤트를 내보내고 부모가 대신 값을 변경합니다.

언급URL : https://stackoverflow.com/questions/50287826/vue-router-passing-data-to-another-component

반응형