VUE2对话框没弹出来的时候通过ref找不到对话框内部的元素?

<el-dialog :title="title" :visible.sync="open" width="500px" v-dialogDrag append-to-body>
<input type="file" ref="photoFile" accept="image/jpeg,image/jpg,image/png" multiple @change="selectFile($event)"/>
<img ref="preView" style="max-width:80%"/>
....

如题,我想对话框弹出之前,想清空input,img的内容

      this.$refs.preView.src ="";
      this.$refs.photoFile.value="";

this.$refs里找不到preView,photoFile
这个是啥子原理

阅读 2.2k
2 个回答

这是因为对话框弹出之前没这个这个DOM, 既然都使用Vue了, 为什么还要操作DOM呢 ,完全可以这么写以img举例, :
<img :src="imgSrc" style="max-width:80%"/>
弹出前:this.imgSrc = ''

在 Vue 2 中,当对话框还没有弹出来时,其内部的元素是无法通过 ref 找到的。这是因为 Vue 组件在初始化时,还没有被挂载到 DOM 上,所以无法访问到组件内部的 DOM 元素。

如果你需要在对话框弹出后访问对话框内部的元素,可以考虑在对话框的 shown 事件中进行操作,该事件会在对话框显示出来后被触发。例如:

vue
Copy code
<template>
<el-dialog :visible.sync="dialogVisible" @shown="onDialogShown">

<div ref="dialogContent">
  <!-- 对话框内容 -->
</div>

</el-dialog>
</template>

<script>
export default {
data() {

return {
  dialogVisible: false
}

},
methods: {

onDialogShown() {
  // 对话框显示后,可以访问对话框内部的元素
  const dialogContent = this.$refs.dialogContent
  // ...
}

}
}
</script>
在上面的示例中,我们在对话框的 shown 事件中访问了对话框内部的元素,通过 $refs 获取了对话框内容的 DOM 元素。当对话框显示出来后,该事件会被触发,我们就可以在事件处理函数中访问对话框内部的元素了。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题