2017-01-23 52 views
1

我在這裏試圖實現的是,當我點擊Item-card-product-choices.vue中的項目時,它將觸發selectPC,參數productChoice.id,這也會觸發父母收聽這個事件並且在同一時間得到參數。我按照the doc做但父母似乎不聽selectPC。所以請解決以下問題senpai:Vue2 Laravel5.3如何發送數據從小孩到父母的事件

  1. 我的方式爲家長傾聽孩子的事件有什麼問題嗎?
  2. 當父母監聽時,如何獲得孩子在事件中使用的參數呢? 謝謝。

項目 - 卡產品choices.vue

<template> 
    <ul class="product-choices"> 
    <li 
    v-for="productChoice in productChoices" 
    class="product-choice" 
    @click.prevent="selectPC(productChoice.id)" 
    > 
     <svg v-if="productChoice.color === 'red'" width="20" height="20"> 
     <rect width="20" height="20" style="fill:#FF3333"></rect> 
     </svg> 
     ...... 
     ...... 
     ...... 
    </li> 
    </ul> 
</template> 

<script> 
    export default { 
    props:[ 
     'index', 
     'product' 
    ], 
    data() { 
     return { 
     productChoices:{}, 
     } 
    }, 
    methods:{ 
     selectPC(productChoice){ 
     var vm = this; 
     vm.$emit('select',productChoice) 
     }, 
    } 
    } 
</script> 

Parent.vue

<template> 
    <div> 
    .... 
    <product-choices :product="product" @selectPC="getSelected(productChoice)"></product-choices> 
    .... 
    </div> 
</template> 

<script> 
    import productChoices from './Item-card-product-choices.vue'; 
    export default { 
    components:{ 
     'product-choices':productChoices 
    }, 
    data(){ 
     return{ 
     productChoiceSelected:{}, 
     } 
    }, 
    methods:{ 
     getSelected(selected){ 
     var vm = this 
      alert(1) // this is what I added to test if it listens 
     vm.$on('select',function(selected){ 
      vm.$http.get('/getProductChoice/'+vm.product.id+'/'+selected).then((response)=>{ 
      vm.productChoiceSelected = response.data 
      }); 
     }) 
     } 
    } 
</script> 

回答

1

你發射被命名事件 「選擇」,而不是 「selectPC」 所以你需要Parent.vue

<product-choices :product="product" @select="getSelected"></product-choices> 

你聽爲方法不應該添加一個$on聽衆要麼...

getSelected(selected) { 
    this.$http.get('/getProductChoice/' + this.product.id + '/' + selected).then(response => { 
    this.productChoiceSelected = response.data 
    }) 
} 
+0

所以,如果我不使用'emit' $,根據我共享文檔,家長其實可以聽聽孩子正確的方法?那不是我在我的代碼中做的事情嗎? – warmjaijai

+0

@warmjaijai子組件仍然需要'$ emit'事件。正如它在你分享的文檔中所說的那樣... [*「你不能使用'$ on'來監聽兒童發出的事件,你必須直接在模板」*「中使用'v-on'(https:// vuejs.org/v2/guide/components.html#Using-v-on-with-Custom-Events)。注意,'@select =「...」'與'v-on:select =「...」相同'' – Phil

+0

哦,我看到現在在代碼中發出了,在doc中方法增量和發出增量使我困惑。現在讓我試試你的建議,謝謝@Phil – warmjaijai

相關問題