2017-09-05 2 views
0

evntbus를 사용하여 두 구성 요소간에 데이터를 전달합니다. 버튼을 클릭하면 제출 된 기능이 실행되고 다른 구성 요소에 객체 배열이 전송됩니다. vue js에서 eventbus와 함께 전송 된 객체의 액세스 값

submitted(){ 
    this.products.push(this.product); 
    EventBus.$emit('prod', this.products); 
} 

다른 성분

:

created(){ 
    EventBus.$on('prod', function (productObject) { 
    console.log('event received!', userObject); 
    this.produc = productObject.products 
    console.log('The product: ', this.produc) 
    }.bind(this)); 
    console.log('User outside eventbus:', this.produc); 
} 

문제가 나는 두 번째 구성 요소로 전달 eventbus 객체에 액세스 할 수 있다는 것이다 못해 어느 누구도 도와 줘? productobject의 값은 당신이 아니라 구성 요소의 EventBus에 이벤트를 방출로는, EventBus.$emit('prod', this.products);해야한다,

image

+0

는 콘솔에'productObject'를 기록 할 수 있습니다? 'products' 속성을 포함하고 있는지 또는 배열인지 확신합니까? – Tomer

+0

https://i.stack.imgur.com/22hl7.png – mar

+0

첨부 한 로그에서 볼 때, productObject는 하나의 요소를 가진 배열이며, 'this.product'가 아니라'this.products'를 출력합니다. – raina77ow

답변

1

처음이다.

두 번째로 이벤트 버스에 this.products (배열)을 전달하지만 핸들러 함수에서이 코드를 단일 객체로 처리하는 것처럼 보입니다. 게다가, 당신은 그것의 임의의 가치 (제품)에 접근하려하고 있는데, 분명히 이벤트 데이터 객체가 어떤 변수를 저장했는지 기억하고 있다고 생각합니다. 그러나 그렇지 않습니다.

그래서, 당신은 실제로 EventBus로 제품의 전체 배열을 전달할 필요가 있는지 여부에 따라 두 가지 옵션이 있습니다

1) 다른 곳 this.products을해야하는 경우, 그 다른 구성 요소에 마지막 요소에 액세스를 :

EventBus.$on('prod', function(products) { 
    this.product = products[products.length - 1]; 
    console.log('The product: ', this.product); 
}.bind(this)); 

2)하지 않을 경우 단지 하나의 제품을 보내 직접 사용

EventBus.$emit('prod', this.product); 

// ...and in another component 
EventBus.$on('prod', function(product) { 
    this.product = product; 
    console.log('The product: ', this.product); 
}.bind(this)); 
+0

귀하의 응답 thnx 표시됩니다 내가 코드를 복사 할 때 나는 당신이 말한 것처럼 쓸하지만 난 두 번째 구성 요소의 값을 액세스 할 수 없습니다 – mar

관련 문제