vue.js子组件修改父组件传进来的props

我在做仿饿了吗vue的项目,其中ratingselect模块的要修改food模块传进来的props值

我是这么做的:
food父模块:
html

<ratingselect :select-type="selectType" :only-content="onlyContent" :desc="desc" :ratings="food.ratings"></ratingselect>

js

eventBus.$on('ratingtype.select', (type) => {
    this.selectType = type;
    this.$nextTick(() => {
        this.scroll.refresh();
    });
});
 eventBus.$on('content.toggle', (onlyContent) => {
    this.onlyContent = onlyContent;
    this.$nextTick(() => {
         this.scroll.refresh();
    });
});

ratingselect子模块
html

<div class="ratingselect">
    <div class="rating-type">
        <span @click="select(2,$event)" class="block positive" :class="{'active':selectType===2}">{{desc.all}}<span class="count">{{ratings.length}}</span></span>
        <span @click="select(0,$event)" class="block positive" :class="{'active':selectType===0}">{{desc.positive}}<span class="count">{{positives.length}}</span></span>
        <span @click="select(1,$event)" class="block negative" :class="{'active':selectType===1}">{{desc.negative}}<span class="count">{{negatives.length}}</span></span>
    </div>
    <div @click="toggleContent" class="switch" :class="{'on':onlyContent}">
        <span class="icon-check_circle"></span>
        <span class="text">只看有内容的评价</span>
    </div>
</div>

js

    methods: {
        select(type, event) {
            if (!event._constructed) {
                return;
            }
            this.selectType = type;
            eventBus.$emit('ratingtype.select', type);
        },
        toggleContent(event) {
            if (!event._constructed) {
                return;
            }
            this.onlyContent = !this.onlyContent;
            eventBus.$emit('content.toggle', this.onlyContent);
        }
    }

实现是可以实现,但是vue2.0不允许子组件修改父组件的传值,怕子组件污染父组件,造成不可控。所以求解决方法

这是报错:

clipboard.png

阅读 7.8k
评论
    6 个回答
    • 307

    通过子组件$emit发射一个方法,在父组件使用子组件的地方用v-on绑定这个自定义事件,然后在父组件定义这个方法,虽然这种方式可以修改父组件数据,但是官方是不推荐在组件内修改通过props传入的父组件数据,而是推荐使用vuex

      相似问题
      推荐文章