报错原因:

所有的 prop 都使得其父子 prop 之间形成了一个单向下行绑定:父级 prop 的更新会向下流动到子组件中,但是反过来则不行。(父组件更新,子组件中的prop值也会更新,但子组件不能修改由父组件传递过来的值)

 解决办法:

    定义一个本地的 data 属性并将这个 prop 用作其初始值,同步对组件的修改,再通知父组件更新

相关代码:

<div class="rating-type">
  <span @click="select(2,$event)" class="block positive" :class="{'active': selectedtype === 2}">{{desc.all}}
    <span class="count">47</span>
  </span>
  <span @click="select(0,$event)" class="block positive" :class="{'active': selectedtype === 0}">{{desc.positive}}
    <span class="count">50</span>
  </span>
  <span @click="select(1,$event)" class="block negative" :class="{'active': selectedtype === 1}">{{desc.negative}}
    <span class="count">47</span>
  </span>
</div>

 子组件:

data() {
  return {
    typeSelected: this.selectType,
    contOnly: this.onlyContent
  };
},
methods: {
  select(type, event) {
    if (!event._constructed) {
      return;
    }
    this.typeSelected = type;
    this.$emit('change', type);
  },
  toggleContent(event) {
    if (!event._constructed) {
      return;
    }
    this.contOnly = !this.contOnly;
    this.$emit('toggle', this.contOnly);
  }
}

父组件:

<ratingselect :select-type="selectType" :only-content="onlyContent"
:desc="desc" :ratings="food.ratings"
 @change="change" @toggle="toggle"></ratingselect>
methods: {
  //  子组件更新的值
  change(type) {
    this.selectType = type;
  },
  toggle(val) {
    this.onlyContent = val;
  },
  //  子组件更新的值==结束

效果图:

官方文档链接:https://cn.vuejs.org/v2/guide/components-props.html

Logo

前往低代码交流专区

更多推荐