How to solve [Vue warn]: Avoid mutating a prop directly since the value will be overwritten on vue.js 2?

后端 未结 3 957
北海茫月
北海茫月 2020-12-20 20:51

My view is like this :

... ...
相关标签:
3条回答
  • 2020-12-20 21:28

    You need to make the computed with a getter and a setter and then use $emit to update the prop e.g:

        computed: {
            starValue:{ 
                get:function () {
                    return this.temp_value
                },
                set: function(newValue){
                    // $emit is the correct way to update props:
                    this.$emit('update:value', newValue);
                }
            }
        }
    
    0 讨论(0)
  • 2020-12-20 21:40

    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:

    methods: {
      rate: function (star) {
        var self = this;
        if (!this.disabled) {
            this.$http.post(window.BaseUrl + '/star', {star: star}).then(function (response) {
                console.log('submitted');
            });
            this.temp_value = star;
            // return this.value = star; - remove this line
        }
      }
    }
    

    and add a computed property like so:

    computed: {
      starValue () {
        return this.temp_value
      }
    }
    
    0 讨论(0)
  • 2020-12-20 21:46

    You're changing the value property here.

    return this.value = star;
    

    And possibly here.

    v-model="value"
    

    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.

    0 讨论(0)
提交回复
热议问题