2016-11-11 55 views
1

我剛剛開始使用Vue.js,經過相當長時間的嘗試,我無法弄清楚如何從組件向vue實例傳遞某些東西。 我使用這個組件作爲一個評級系統,但我不知道如何獲得的電流值,以我的主要實例 (https://fiddle.jshell.net/swyuarc9/vue組件和vue實例之間的通信

Vue.component('star-rating', { 

    props: { 
    'name': String, 
    'value': null, 
    'id': String, 
    'disabled': Boolean, 
    'required': Boolean 
    }, 

    template: '<div class="star-rating">\ 
     <label class="star-rating__star" v-for="rating in ratings" \ 
     :class="{\'is-selected\': ((value >= rating) && value != null), \'is-disabled\': disabled}" \ 
     v-on:click="set(rating)" v-on:mouseover="star_over(rating)" v-on:mouseout="star_out">\ 
     <input class="star-rating star-rating__checkbox" type="radio" :value="rating" :name="name" \ 
     v-model="value" :disabled="disabled">★</label></div>', 

    /* 
    * Initial state of the component's data. 
    */ 
    data: function() { 
    return { 
     temp_value: null, 
     ratings: [1, 2, 3, 4, 5] 
    }; 
    }, 

    methods: { 
    /* 
    * Behaviour of the stars on mouseover. 
    */ 
    star_over: function(index) { 
     var self = this; 

     if (!this.disabled) { 
     this.temp_value = this.value; 
     return this.value = index; 
     } 

    }, 

    /* 
    * Behaviour of the stars on mouseout. 
    */ 
    star_out: function() { 
     var self = this; 

     if (!this.disabled) { 
     return this.value = this.temp_value; 
     } 
    }, 

    /* 
    * Set the rating of the score 
    */ 
    set: function(value) { 
     var self = this; 

     if (!this.disabled) { 
     // Make some call to a Laravel API using Vue.Resource 

     this.temp_value = value; 
     return this.value = value; 
     } 
    } 
    } 

}); 

new Vue({ 
    el: '#app' 
}); 

回答

1

歡迎的Vue!

起初可能會有點困難,但您傳遞屬性的方式是通過props。爲此,您需要首先在您的父級(本例中爲您的應用程序實例)上定義一個data對象。

vue-docs中有一些很好的道具例子。
在一般情況下,這是你怎麼做:

new Vue({ 
    el: '#app', 
    data: function() { 
    return { 
     foo: 'Foo' 
    } 
    } 
}); 

Vue.component('bar', { 
    props: { foo: String }, 
    template: '<span> {{ foo }}</span>' 
}) 

...和HTML

<div id="app"> 
    <bar :foo="foo"></bar< 
</div> 

我分叉的小提琴,並增加了演示道具,只是讓你看到它的行動。 Check it out

+0

(更新的叉鏈接,SOZ) –

+0

你確定你鏈接的人工作嗎?如果我將鼠標懸停在星星上,沒有任何反應。 – Tom00

+0

我沒有繼續實施你的解決方案(甚至不知道它應該如何工作),我只是添加了一個示例來展示如何在comp之間共享數據。這取決於你實施正確的行爲:-) –