避免直接改变道具

时间:2019-06-25 11:21:00

标签: javascript laravel vue.js

我收到警告:

app.js:87486 [Vue警告]:避免直接更改道具,因为每当父组件重新渲染时,该值就会被覆盖。而是使用基于属性值的数据或计算属性。道具被变异:“ likescount”

我的刀片

        <path-like-toggle likescount="{{$path->likeCount}}" isliked="{{$path->canBeunLiked()}}" path="{{$path->slug}}" type="{{$path->type}}" ></path-like-toggle>

Vue代码

      props:['isliked','path','type','likescount']
    ,
methods:{
         like () {
             axios.post(`/${this.type}/${this.path}/like/`)
                this.likingStatus = true;
                this.likescount ++;
        },
         unlike () {
             axios.post(`/${this.type}/${this.path}/unlike/`)
                this.likingStatus = false;
                this.likescount --;

        },
    }

2 个答案:

答案 0 :(得分:3)

从道具中初始化数据属性,然后对其进行操作。

export default {
    data() {
        return {
            numberOfLikes: this.likescount
        }
    },

    props: [
        'isliked',
        'path',
        'type',
        'likescount'
    ],

    methods:{
        like() {
            axios.post(`/${this.type}/${this.path}/like/`);

            // ...

            this.numberOfLikes++;
        },

        unlike() {
            axios.post(`/${this.type}/${this.path}/unlike/`);

            // ...

            this.numberOfLikes--;
        },
    }
}

答案 1 :(得分:0)

正如警告所言,您不得变异道具,将其移除 this.likescount ++; this.likescount-;

这将消除警告...您的道具应该是纯正的