My view is like this :
<div class="col-md-8">
...
<star :value="{{ $data['rating'] }}"></star>
...
</div>
My star component is like this :
<template>
<span class="rating" :class='{"disable-all-rating": !!value}'>
<template v-for="item in items">
<label class="radio-inline input-star" :class="{'is-selected': ((starValue>= item.value) && starValue!= null)}">
<input type="radio" class="input-rating" v-model="starValue" @click="rate(item.value)">
</label>
</template>
</span>
</template>
<script>
export default{
props: {
'value': null
},
computed: {
starValue () {
return this.temp_value
}
},
data(){
return{
items: [
{value: 5},
{value: 4},
{value: 3},
{value: 2},
{value: 1}
],
temp_value: null,
}
},
methods:{
rate: function (star) {
this.$http.post(window.BaseUrl + '/star', {star: star});
this.temp_value = star;
},
}
}
</script>
My css is like this :
span.rating {
direction: rtl;
display: inline-block;
}
span.rating .input-star {
background: url("../img/star.png") 0 -16px;
padding-left: 0;
margin-left: 0;
width: 16px;
height: 16px;
}
span.rating .input-star:hover, span.rating .input-star:hover ~ .input-star {
background-position: 0 0;
}
span.rating .is-selected{
background-position: 0 0;
}
span.rating .is-disabled{
cursor: default;
}
span.rating .input-star .input-rating {
display: none;
}
When I click the star, there exist error on the console like this :
[Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "value" (found in at C:\xampp\htdocs\myshop\resources\assets\js\components\Star.vue)
How can I solve it?
You're changing the
value
property here.And possibly here.
The warning means that whenever your view is re-rendered, the
value
property is going to be set to$data['rating']
, overwriting whatever you did inside the start component.Instead of mutating the property inside your component, when someone clicks a star, you probably want to
$emit
that the component has changed and let your view change$data['rating']
, which will re-render the star component properly.See the Vue documentation regarding component composition.
The warning suggests not modifying a prop's value directly as doing so you would lose the change anyway if the data at the parent component changes.
That said, here in your method:
and add a computed property like so:
You need to make the computed with a getter and a setter and then use
$emit
to update the prop e.g: