如何解决 \[Vue warn\]: Avoid mutating a prop directly since the value will be overwritten on vue.js 2?

新手上路,请多包涵

我的观点是这样的:

 <div class="col-md-8">
    ...
        <star :value="{{ $data['rating'] }}"></star>
    ...
</div>

我的明星组件是这样的:

 <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>

我的 CSS 是这样的:

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

当我点击星标时,控制台上存在这样的错误:

[Vue warn]:避免直接修改 prop,因为只要父组件重新渲染,该值就会被覆盖。相反,使用基于 prop 值的数据或计算属性。 Prop 被改变:“value”(位于 C:\xampp\htdocs\myshop\resources\assets\js\components\Star.vue)

我该如何解决?

原文由 samuel toh 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 450
1 个回答

您需要使用 getter 和 setter 进行计算,然后使用 $emit 更新道具,例如:

     computed: {
        starValue:{
            get:function () {
                return this.temp_value
            },
            set: function(newValue){
                // $emit is the correct way to update props:
                this.$emit('update:value', newValue);
            }
        }
    }

原文由 Andy 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题