vue问题错误:[Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the

报错:

Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "selectType"

根据教程vue1.0,ratingselect组件触发自定义事件在父组件food中由event监听事件,实现selectType和onlyContent的传值。

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

在父组件food中代码

,
  events : {
    'ratingtype-select' (type)  {
      this.selectType = type;
      this.$nextTick(() => {
        this.scroll.refresh();
      });
    });
   'content-toggle' (onlycontent)  {
      this.onlyContent = onlycontent;
      this.$nextTick(() => {
        this.scroll.refresh();
      });
    });
  }
  1. 首先vue2.0里面已经弃用了events,事件处理在created钩子中被注册。
  2. 报错ratingselect组件中的变量需要在data或computed中重写。
    Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "selectType"

对应的解决方法

  1. 在ratingselect标签内监听事件并在methods内写回调函数。
  2. 将selectType和onlyContent这俩个需要做修改处理的变量在data中重写。

ratingselect子组件接收数据,修改数据,然后设置派发事件将修改后的数据派发的父组件

ratingSelect.vue(子组件中),在子组件中除了用props接收父子间的数据之外,还要在data中定义两个变量,将props中接收到的值赋值给这两个新变量,之后在子组件中改变的都是这两个新的变量

data () {
    return {
      stype: this.selectType,
      ocontent: this.onlyContent
    };
  }

methods: {
    select (type, event) {
      if (!event._constructed) {
        return;
      }
      this.stype = type;
      this.$emit('ratingevent', 'selectType', this.stype);
    },
    toggleContent (event) {
      if (!event._constructed) {
        return;
      }
      this.ocontent = !this.ocontent;
      this.$emit('ratingevent', 'onlyContent', this.ocontent);
    }
  }

food组件做如下修改

  {
        this.scroll.refresh();
        // 异步让滚动刷新
      });
    }

会不会好奇不是说把event的事件处理在created中注册了吗,为啥不用created呢?
我参考众多的资料,觉得是因为created函数的生命周期在实例创建之后,而此时实例已经创建完成,不会调用该函数,还有一种方式是可以在触发事件的方式改为事件中心,这样应该可以监听到。
目前大多数的事件处理通过v-on来监听,调用对应的回调函数实现.

你可能感兴趣的:(vue)