目录
关键词
问题发现
解法探寻
解决办法
关键词
element ui plus,props,vue3,
问题发现
当父组件向子组件传递布尔值visible来控制子组件可见性的时候,发现似乎不可行:
r
<template>
<el-dialog :v-model="visible" >
<span>呀哈</span>
</el-dialog>
</template>
<script>
import EleUploadVideo from "@/components/EleUploadVideo.vue";
export default {
name: 'VideoUploadPopup',
components: {
EleUploadVideo,
},
props: {
visible: {
type: Boolean,
required: true
},
point:{
type:Object,
default: null // 设置默认值为空对象或者 null
}
},
emits: ['closePopup', 'deletePoint'], // 声明自定义事件
data() {
return {
token: 'xxx',
video: 'https://s3.pstatp.com/aweme/resource/web/static/image/index/tvc-v2_30097df.mp4'
};
},
computed: {
uploadData() {
return {
token: this.token
};
}
},
methods: {
}
};
</script>
<style scoped>
</style>
解法探寻
查询element ui 官网,发现是用v-model没错,而且vue3里面似乎不用:visible-sync了:
Dialog 对话框 | Element Plus
然后看了另外的文章,发现子组件不能直接更改props里面的数据,也不能直接进行v-model绑定
el-dialog作为子组件如何由父组件控制显示/隐藏_公共组件的dialog是父组件的dialog进行传值来显示title和显示隐藏-CSDN博客
解决办法
- 在子组件内部多写一个变量来和v-model绑定,并且将父组件props的值发给该变量
- 父子组件赋值的过程在mounted里面调用
看代码~
r
<template>
<el-dialog
title="乌萨奇:"
v-model="dialogVisible"//看这里!
append-to-body="true">
<span>测试文字</span>
</el-dialog>
</template>
<script>
export default {
name: 'VideoUploadPopup',
props: {
visible: {//接受父级组件的显示标记,用于被watch
type: Boolean,
required:true
},
point: {
type: Object,
default: null
}
},
emits: ['closePopup', 'deletePoint'],
data() {
return {
token: 'xxx',
dialogVisible: false,
video: 'https://s3.pstatp.com/aweme/resource/web/static/image/index/tvc-v2_30097df.mp4'
};
},
computed: {
uploadData() {
return {
token: this.token
};
}
},
mounted(){//看这里!!
console.log(this.visible);
this.dialogVisible = this.visible;
console.log("mounted后dialogVisible的新值为:",this.dialogVisible);
},
watch: {
visible(newVal) {
this.dialogVisible = newVal; // 监听 visible 变化,并将新值赋给 dialogVisible
console.log("watch后dialogVisible的新值为:", this.dialogVisible)
}
},
methods: {
},
};
</script>
<style scoped>
/* 样式 */
</style>
重点关注这两段代码:
mounted(){
console.log(this.visible);
this.dialogVisible = this.visible;
console.log("mounted后dialogVisible的新值为:",this.dialogVisible);
},
watch: {
visible(newVal) {
this.dialogVisible = newVal; // 监听 visible 变化,并将新值赋给 dialogVisible
console.log("watch后dialogVisible的新值为:", this.dialogVisible)//调试过程证明
}
},
成品展示如下:
注意看调试窗口里面:当visible的值发生变化的时候,没有调用watch的函数,而是调用mounted函数
个人经验,如有错漏,欢迎指出