2017-09-23 4 views
0

부모 구성 요소 렌더링 방법을 알아 내고 페이지 일부의 목록에 계약 목록을 표시하고 사용자가 그 중 하나를 클릭하면 문제가 발생합니다. 특정 계약의 세부 사항을 페이지의 다른 부분에 표시하십시오.vue.js 구성 요소 렌더링 및 데이터 전달

#contracts_area 
    .filter-section 
    ul 
     li.filter-item v-for="contract in contractsAry" :key="contract.id" @click="showContract(contract)" 
     | {{ contract.name }} 
    .display-section 
    component :is="currentView" transition="fade" transition-mode="out-in" 

script type="text/x-template" id="manage-contracts-template" 
    div 
    h1 Blank when page is newly loaded for now 

script type="text/x-template" id="view-contract-template" 
    div :apply_contract="showContract" 
    h1#display-item__name v-name="name" 

자바 스크립트 : 사용자가 .filter 섹션의 모든 계약 항목을 클릭 할 때 있도록

기본적으로
Vue.component('manage-template', { 
    template: '#manage-contracts-template' 
    }); 

    Vue.component('view-contract', { 
    template: '#view-contract-template', 
    props: ['show_contract'], 
    data: function() { 
     return { 
     name: '' 
     } 
    }, 
    methods: { 
     showContract: function(contract) { 
     return this.name = contract.name 
     } 
    } 
    }); 

    Vue.http.headers.common['X-CSRF-Token'] = $('meta[name="csrf-token"]').attr('content'); 
    var contractsResource = Vue.resource('/all_contracts{/id}.json'); 

    var contracts = new Vue({ 
    el: '#contracts_area', 
    data: { 
     currentView: 'manage-template', 
     contractsAry: [], 
     errors: {} 
    }, 
    mounted: function() { 
     var that = this; 
     contractsResource.get().then(
     function(res) { 
      that.contractsAry = res.data; 
     } 
    ) 
    }, 
    methods: { 
     showContract: function(contract) { 
     this.currentView = 'view-contract' 
     } 
    } 
    }); 

내가 그것을 그것을 싶습니다 여기

내 슬림 파일입니다 .display-section에서 해당 계약의 데이터를 보여줍니다. 이것을 어떻게 할 수 있습니까?

답변

1

간단히 말해 값을 prop에 바인딩 할 수 있습니다.

.display-section 
    component :is="currentView" :contract="currentContract" 

보기 계약

props: ['contract'] 

계약 면적

data: { 
    currentContract: null, 
}, 
methods: { 
    showContract: function(contract) { 
    this.currentView = "view-contract"; 
    this.currentContract = contract; 
    } 
} 

는 뷰에 데이터를 전달하기 위해 여러 가지 방법이 있습니다.

  1. 바인딩 값은 props입니다.
  2. ref을 사용하여 하위 구성 요소에서 직접 메서드를 호출합니다.
  3. Custom Events. 이벤트를 전 세계적으로 전달하려면 전역 이벤트 버스가 필요합니다.
  4. 진실의 단일 중앙 소스 (즉, vuex)
  5. 나는 방법 1, 2, 3 2 차 및 3 번째 방법은 후에 만 ​​작동합니다 참고

    Codepen에에게 설명했다

구성 요소가 렌더링되었습니다. 귀하의 경우 currentView 구성 요소가 동적이며 사용자가 클릭 할 때 display-section 구성 요소가 아직 존재하지 않으므로; 아직 어떤 이벤트도 수신하지 않습니다. 그래서 그들의 내용은 처음에는 비어있을 것입니다.

이 문제를 해결하려면 하위 구성 요소에서 $parentmounted()에 직접 액세스 할 수 있습니다. 또 다른 솔루션은 구성 요소를 만들고 있지만 conditionally displaying입니다. 또 다른 해결책은 자식 구성 요소가 마운트 된 다음 이벤트가 발생할 때까지 대기하는 것입니다.

귀하의 필요가 간단하다면 소품()에 바인딩 값을 제안하십시오. 그렇지 않으면 vuex와 같은 것을 사용하는 것이 좋습니다.

+0

완벽한, 고맙습니다. 그리고 Vue를 시작하면서 심오한 답변, 거대한 도움을 주셔서 감사합니다. – asalgan

관련 문제