解决 [Vue warn]:Avoid mutating a prop directly 警告

错误信息

解决 [Vue warn]:Avoid mutating a prop directly 警告_第1张图片

[Vue warn]: 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: “xxx”

错误原因

所有的 prop 都使得其父子 prop 之间形成了一个单向下行绑定:父级 prop 的更新会向下流动到子组件中,但是反过来则不行。这样会防止从子组件意外变更父级组件的状态,从而导致你的应用的数据流向难以理解。

额外的,每次父级组件发生变更时,子组件中所有的 prop 都将会刷新为最新的值。这意味着你不应该在一个子组件内部改变 prop。如果你这样做了,Vue 会在浏览器的控制台中发出警告。

vue文档链接: https://v2.cn.vuejs.org/v2/guide/components-props.html#%E5%8D%95%E5%90%91%E6%95%B0%E6%8D%AE%E6%B5%81

解决方案

父组件

组件调用时,通过update接受子组件传递的值变化

//父组件调用
<select-cost-center :selected-cost-center="selectedCostCenter" @update:selectedCostCenter="selectedCostCenterUpdate">
</select-cost-center>

export default {
  components: {
    selectCostCenter
  },
  methods: {
	//监听组件选择成本中心
	selectedCostCenterUpdate(selectedCostCenter) {
    	this.selectedCostCenter = selectedCostCenter;
  	}
  }
}
子组件

父组件传递的prop使用另一个data接受,并在修改时给父组件传递消息


export default {
  name: "selectCostCenter",
  props: {
  	//接收的prop
    selectedCostCenter: Object
  },
  data: function () {
    return {
      //使用另一个参数处理父组件传递的prop
      selected: this.selectedCostCenter
    }
  },
  methods: {
    //使用$emit通知父组件修改prop对应的值
    handleCostCenterChange(item) {
      this.selected = item;
      this.$emit("update:selectedCostCenter", this.selected);
    },
  }

问题解决的话,请点个赞吧

最后

另外需要注意在 JavaScript 中对象和数组是通过引用传入的,所以对于一个数组或对象类型的 prop 来说,在子组件中改变变更这个对象或数组本身将会影响到父组件的状态。

你可能感兴趣的:(vue.js,javascript,前端)