Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

All prop forms a one-way downlink binding between their parent prop: updates to the parent prop flow down to the child, but not the other way around. This prevents accidental changes in the state of the parent component from the child, which can make the data flow of your application difficult to understand.

Additionally, every time the parent component changes, all prop in the child component will be refreshed to the latest value. This means that you should not change a prop inside a child component. If you do, Vue will issue a warning in the browser console. Error as follows:

The solution

(1) Redefine data in data

This applies when prop is used to pass an initial value; This child component next wants to use it as a local prop data. In this case, it is best to define a local data Property and use this prop as its initial value:

props: ['initialCounter'].data: function () {
  return {
    counter: this.initialCounter
  }
}
Copy the code

(2) by calculating attributes

This prop is passed in as a raw value and needs to be converted. In this case, it is best to use the value of this prop to define a calculated property:

props: ['size'].computed: {
  normalizedSize: function () {
    return this.size.trim().toLowerCase()
  }
}
Copy the code

(3) via the $emit event

The parent component:

<template>/ / the parent component
   <CommonDialog
     :title="dialogTitle"
     :showDialog.sync="isShowDialog"
     :footer="true"
     :width="dialogWidth"
   >.</CommonDialog>
</template>
Copy the code

Child components

// Whether to open the props: showDialog subcomponent
<el-dialog :title="title" :visible="showDialog" :show-close="false" :width="width">
  <i class="el-dialog__headerbtn" @click="closeModal">
    <span class="iconfont iconclose"></span>
  </i>
  <div class="dialog-body">
      <slot></slot>
  </div>
  <div v-if=! "" footer" slot="footer" class="dialog-footer">
    <slot name="footer"></slot>
  </div>
</el-dialog>
Copy the code

Events:

closeModal() {
   this.$emit("update:showDialog".false);
 },
Copy the code