2017-06-13 55 views
1

Vue.js非常新,我有問題將子對象的事件處理函數傳遞給它的直接父對象。我有一個滑塊,我想將其值傳遞給它的父組件。當我運行我的代碼時,我將'孩子'打印到控制檯而不是'父母',因此顯然聽不到正確的。

new Vue({ 
 
    el: '#price-filter-container', 
 
    data() { 
 
    return { 
 
     value: [0, Products.maxPrice], 
 
     min: 0, 
 
     max: Products.maxPrice, 
 
     products: [Products.products] 
 
    } 
 
    }, 
 
    methods: { 
 
    sliderChange: function(data) { 
 
     console.log("parent") 
 
    } 
 
    } 
 
}); 
 

 
Vue.component('price-filter', { 
 
     props: ['value', 'min', 'max', 'products'], 
 
     template: '<vue-slider v-on:click.native="childSliderChange" v-model="value" :min="min" :max="max"></vue-slider>', 
 
     methods: { 
 
     childSliderChange: function() { 
 
      console.log("child"); 
 
      this.$emit('childSliderChange'); 
 
     } 
 
     }, 
 
    });
<div id="app" style="margin-top:20px;width:1000px"> 
 
    <div id="price-filter-container" style="width:300px;margin:50px auto;"> 
 
    <price-filter v-on:childSliderChange="sliderChange" :products="products" :max="max" :min="min" :value="value"></price-filter> 
 
    </div> 
 

 
</div>

我完全難倒。爲什麼這不起作用?爲什麼'父'不能打印到控制檯?

+0

'的console.log( 「母公司)'應該是'的console.log(」 母公司「)' – thanksd

+2

試'V系列:兒童滑塊change.camel'它可能是DOM和區分大小寫的問題。https://vuejs.org/v2/api/#v-bind –

+0

@EricGuan'.camel'是'v-bind'和'v-on'的修飾符。 – Bert

回答

1

我建議完全避免使用駱駝事件。發出烤肉串事件並添加烤肉串事件處理程序。

this.$emit('child-slider-change') 

<price-filter v-on:child-slider-change="sliderChange" :products="products" :max="max" :min="min" :value="value"></price-filter> 

這裏有一個基本的例子。

console.clear() 
 

 
Vue.component("emitter",{ 
 
    template:`<h1>I'm the emitter</h1>`, 
 
    mounted(){ 
 
    setTimeout(() => this.$emit('child-slider-change'), 500) 
 
    } 
 
}) 
 

 

 
new Vue({ 
 
    el:"#app", 
 
    data:{ 
 
    caught: null 
 
    } 
 
})
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script> 
 
<div id="app"> 
 
    <emitter @child-slider-change="caught = 'Caught the event'"></emitter> 
 
    {{caught}} 
 
</div>

相關問題