【Vue】报错:Avoid mutating a prop directly since the value will be overwritten whenever the parent

【Vue】报错:Avoid mutating a prop directly since the value will be overwritten whenever the parent,第1张

当我们直接改变父组件的 props 值是会报以下警告:

[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: “facomment”

会报错的原因是由于 Vue 的单项数据流。

怎样理解 Vue 的单项数据流?

数据总是从父组件传到子组件,子组件没有权利修改父组件传过来的数据,只能请求父组件对原始数据进行修改。这样会防止从子组件意外改变父组件的状态,从而导致你的应用的数据流向难以理解。注意: 在子组件直接用 v-model 绑定父组件传过来的 props 这样是不规范的写法,开发环境会报警告。如果实在要改变父组件的 props 值可以再data里面定义一个变量,并用 prop 的值初始化它,之后用$emit 通知父组件去修改。

解决方案:

父组件:

<template>
  <div>
     <BlogComment :facomment="comment" @recordsChange="recordsChange"/>
  div>
template>

<script>
export default {
  name: "BlogDetail",
  components: {
      BlogComment
  },
  data(){
  	return {
  		comment: {},
  	}
  },

  methods: {
  	recordsChange(records) {
        this.comment = records; //在父组件修改值
    },
  }
};
script>

子组件:

<template>
  <div>
    <div class="pagination-box" v-if="facomment.records != null">
          <el-pagination
            background
            layout="prev, pager, next"
            :current-page="facomment.current"
            :page-size="facomment.size"
            :total="facomment.total"
            @current-change="page1"
          >
          el-pagination>
    div>
  div>
template>

<script>
export default {
  name: "",
  props: ["facomment"],

  methods: {
  	// 分页
    page1(page) {
      this.$axios
        .get("/comment/list", {
          params: {
            blogId: this.blogId,
            page: page,
            pageSize: this.pageSize,
          },
        })
        .then((res) => {
          // this.facomment = res.data.data (不能直接修改)
          this.$emit("recordsChange", res.data.data); // 用 $emit 通知父组件去修改
        });
    },
   
  }
};
script>

欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/web/932310.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-17
下一篇2022-05-17

发表评论

登录后才能评论

评论列表(0条)

    保存