【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
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
當我們直接改變父組件的 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-paginationbackgroundlayout="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>總結
以上是生活随笔為你收集整理的【Vue】报错:Avoid mutating a prop directly since the value will be overwritten whenever the parent的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python——快速傅里叶变换
- 下一篇: vue只有package-lock.js