vue 弹框做组件报错

6,966 阅读2分钟

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: "visible"

写一个导入组件的时候,父页面引入该组件,打开弹窗没问题,关闭的时候报如上错误

<template>
    <el-dialog title="导入"
    :visible.sync="visible" :modal-append-to-body="false" :close-on-click-modal="false"  class="dialog-import" >
    </el-dialog>
</template>
export default {
        name: 'upload',
        data () {
            return {
            }
        },
        props:{
          importHeaders: {
            type: Object,
            default: () => {
                return {
                    enctype:'multipart/form-data',
                    cityCode:''
                }
            }
          }
          visible: {
            type: Boolean,
            default: false
          }
        },
        watch: {
        },
        methods: {
        }
    }
</script>

应该是visible 从prop来,不能直接作为v-model吧,他的意思是叫我用data或者computed里转换一下visible当做v-model.

1.我可以在watch里这样写

        watch: {
            visible (newVal) {
                this.visible2 = newVal
            }
        },

然后用visible2当做v-model。这是OK的

2.根据提示的思路写
computed: {
          visible2 () {
            return this.visible
          }
        },

关闭的时候报错 Computed property "visible2" was assigned to but it has no setter.
也就是没有setter咯,那也可以手动加上setter

       computed: {
         visible2: {
           get () {
             return this.visible
           },
           set (val) {
               this.visible = val
           }
         }
       },

也是报错的
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: "visible

3.根据提示思路写
data () {
           return {
               visible2: this.visible
           }
       },

然后用visible2当做v-model。OMYGOD,弹框都不弹了

BUT

方案1 用了之后第一次ok,ele弹框右上边X点击关闭之后,再也弹不出框来了,
弹框做组件总是问题特别多
我想是el-dialog自己的关闭弹框@close,没有跟:visible.sync="visible"同步起来吧。
因为用xx关闭弹框不会改变任何prop的值
所以我加了一个@close事件

<el-dialog title="导入" 
:visible.sync="visible2" 
:modal-append-to-body="false" 
:close-on-click-modal="false"
@close="close" 
class="dialog-import">
</el-dialog>

close () {
               this.visible2 = false
            }

然后,又报错啦!就是它又是它我了个去!
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: "visible" 看这报错 说的也对,prop的值 是你子组件自己能改的嘛!
于是

close () {
                this.$emit('uploadSuccss', 'close')
            }

写在$emit里面,让他爹去改值了
到此,弹框组件圆满了