Tom00 Tom00 - 19 days ago 8
Javascript Question

Communicating between vue component and vue instance

I have just started using Vue.js and after trying for quite some time I can't figure out how to communicate something from a component to the vue instance.
I am using this component as a rating system but I don't understand how to get the current value to my main instance
( https://fiddle.jshell.net/swyuarc9/ )

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'
});

Answer

Welcome to Vue!

It might be a bit harder at first, but the way you pass down properties are via props. To do that, you need to first define a data object on your parent (in this case, your app instance).

There are some good examples on props in the vue-docs.
In general, this is how you do it:

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

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

...and the HTML

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

I forked your fiddle and added a demo prop, just so you see it in action. Check it out.

Comments