VUE报错: Avoid mutating a prop directly since the value will be overwritten whenever the parent及解决方案

VUE报错:[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: "topActive"

大概意思是:避免直接改变属性,因为每当父组件重新渲染时,该值将被覆盖。相反,使用基于属性值的数据或计算属性。通过props传递给子组件的topActive,不能在子组件内部修改props中的topActive值。

<van-tabs
  class="top-tab"
  v-model="topActive"
  v-if="topData"
  @click="topChange"
  title-active-color="#fc5c5c"
  color="#fc5c5c"
>
  <van-tab v-for="(items, key) in topData" :key="key" :title="items.title" :name="items.key" />
</van-tabs>
<script>
export default {
  name: 'ChartTab',
  props: {
    topData: Array,
    topActive: {
      type: String,
      required: true,
    },
  },
}
</script>

修改:不直接使用该参数 通过temp接收该props中的参数 使用temp

<van-tabs
  class="top-tab"
  v-model="activeTopTemp"
  v-if="topData"
  @click="topChange"
  title-active-color="#fc5c5c"
  color="#fc5c5c"
>
  <van-tab v-for="(items, key) in topData" :key="key" :title="items.title" :name="items.key" />
</van-tabs>
<script>
export default {
  name: 'ChartTab',
  props: {
    topData: Array,
    topActive: {
      type: String,
      required: true,
    },
  },
  data() {
    return {
      // 避免直接修改props
      activeTopTemp: this.topActive,
    }
  },
}
</script>

扩展:

v-model通常用于input的双向数据绑定 <input v-model="parentMsg">,也可以实现子组件到父组件数据的双向数据绑定

:model是v-bind:model的缩写

<child :model="msg"></child>这种只是将父组件的数据传递到了子组件,并没有实现子组件和父组件数据的双向绑定。

引用类型除外,子组件改变引用类型的数据的话,父组件也会改变的。

解决vue 子组件修改父组件传来的props值报错问题

报错Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-

v-model和:model的区别

猜你喜欢

转载自blog.csdn.net/yangwqi/article/details/112238528