1. 程式人生 > >[Vue warn]: Avoid mutating a prop directly since the value will be overwritten

[Vue warn]: Avoid mutating a prop directly since the value will be overwritten

使用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: "pageSize"

原因是在使用元件時,傳入的prop,被元件內部又做了一次修改,然後拋的異常,比如如下使用元件的程式碼(修改的是pageSize屬性):

<g-table ref="gTable" :columns="tableColumns"
         highlightCurrentRow
         border
         :page-size="pageSize"
         @g-table-add="handleAddClick"
         @current-change="handleCurrentChange"
         @selection-change="handleSelectionChange"
         url="http://localhost:8888/demo/testGTable"
tooltip-effect="dark"></g-table>

data中配置pageSize=20

然後再元件中的created方法,我修改了這個屬性:

created() {
  this.pageSize = 10;
},

這種情況下就會報這個錯,因為傳入的prop中的值是不允許改變的。這個在vue更新後才會出現的,網上是這麼說的:

在vue2中,直接修改prop是被視作反模式的。由於在新的渲染機制中,每當父元件重新渲染時,子元件都會被覆蓋,所以應該把props看做是不可變物件 ^1。

不能更改 quantity prop使其和父元件同步 , 而是讓應該這個元件提交個事件給父元件,可以 watch quantity 變數,如果變數發生改變就emit事件,所以這裡壓根不需要 prop。