今天在調試代碼時發現控制台經常輸出一個error日志,出於好奇,於是探個究竟。若在你的Vue文件中有如下類似的示例代碼:
<template> <div> <p>Welcome to home</p>
<el-button @click="testButton">Test</el-button> <el-button @click="handleButton">Show Dialog</el-button> <el-dialog :visible.sync="visible" @close="handleClose"> <customer-component ref="customerComponent"/> </el-dialog </div> </template> <script> components: {
'customer-component': ()=>import('HelloWorld') // 假設同目錄下有HelloWorld.vue文件,並且提供了reset()方法
},
data() {
return {
visible: false
}
},
mounted() {
console.log('====this refs are', this.$refs)
},
methods: {
testButton() {
this.$refs.customerComponent.reset()
},
handleButton(){
this.visible = true
},
handleClose() {
this.visible = false
}
} <script> <style> </style>
(1)問題現象
當進入該組件后,先不要彈出對話框,而是直接觸擊estButton()方法,此時會在控制台中看到一條error消息,如下截圖所示:
也就是說this.$refs.cusomerComponent是undefined,未定義的,不能直接引用reset()方法。
(2)問題分析
由於該組件中是通過this.visible屬性值來控制對話框的,當首次進入該組件時,由於this.visible為false,所以對話框中插槽內容是不會被渲染的,我們也可以在mounted方法看到console.log()對this.$refs的打印,發現是空的。所以可以肯定的一點是當el-dialog組件通過visible屬性來控制顯示時,若初始值時false的話,那么首次進入父組件時該el-dialog組件內的內容是不會被加載渲染的,此時不能直接使用ref來訪問插槽中組件的方法或者屬性。
(3)問題解決
通過分析,已明確問題的原因了,那么我們可以這樣來處理:首先判斷this.$refs.customerComponent是否有效,若無效的話,就不執行reset()方法;所以,在testButton()方法中適當判斷一下就可以了:
testButton() { if (this.$refs.customerComponent) { this.$refs.customerComponent.reset() } }