vue封装Dialog子组件报警告问题

286 阅读1分钟

[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: "dialogVisible"

3JMncgMuBc.jpg

visible.sync问题

子组件

1.visible.sync语法糖简单介绍

  1. <child-dialog :visible.sync="visible"></child-dialog>
  2. 等同于
  3. <child-dialog :visible="visible" @update:visible="val => visible = val"></child-dialog>

2.在VUE中,prop的传递是父传给子,属于单向传输,而关闭事件在子组件里,一般情况下需要通过this.$emit来实现子组件向父组件通信
3.sync指令其实是调用了父组件里写的update,从而实现visible的父子同步,父组件初始化visible,子组件调用关闭事件,触发父组件的update
4.双向绑定v-modal触发的是父组件input事件,.sync触发的是父组件的update事件.

<el-dialog :custom-class="customClass" :title="title" :visible="dialogVisible" :width="width" @close="handleClose">
      <el-scrollbar class="scroll_box">
        <ul class="tips">
          <li class="tip" v-for="(item, index) in failList" :key="index">
            <ul class="cols">
              <li class="col_tip" v-for="(colItems, colIndex) in Object.values(item)" :key="colIndex">
                <p>
                  <span>第{{ colItems[0].rowIdx }}行</span>
                  <span v-for="(colItem, nameIndex) in colItems" :key="nameIndex">
                    {{ nameIndex === 0 ? ':' : ',' }}字段 {{ colItem.colName }}&nbsp;
                    {{ getMsg(colItem) }}
                  </span>
                </p>
              </li>
            </ul>
          </li>
        </ul>
      </el-scrollbar>
    </el-dialog>

警告原因是因为子组件中使用了:visible.sync,直接用:visible即可