1. 程式人生 > 其它 >uni-app開發中 this.$refs 用不了

uni-app開發中 this.$refs 用不了

技術標籤:uni-appvue.js小程式

"this.$refs.xxxx"呼叫子元件無效的可能原因

1. ref繫結的物件是否正確

<templete>
	<view ref="child"></view>
</templete>
<script>
	export default {
		onLoad(){
			// 會報 "child is undefined" 的問題
			console.log(this.$refs.child)
		}
	}
</script>

問題:
這個是因為uniapp的ref屬性不能用在uniapp的內建元件上面,只能用在自定義元件上面

2. 繫結物件的是否存在v-if

<templete>
	<song-player ref="songPlayer" v-if="show" />
</templete>
<script>
	import songPlayer from "xxxxx/xxx/xxx.vue"
	export default {
		data(){
			return{
				show: false
			}
}, components: { songPlayer }, onLoad(){ // 會報 "voicePlay is undefined" 的問題 console.log(this.$refs.songPlayer) } } </script>

問題:

此處的songPlayer 無法獲取原因是由於v-if的存在導致此處元件並不存在,自然ref屬性也不存在。
如果使用v-show就可以解決這個問題,但是這會導致元件的created()提前觸發,請斟酌使用

3.執行中報錯undefined

需要新增 this.$nextTick(()=>{})

<templete>
	<voice-play ref="songPlayer" />
</templete>
<script>
	import songPlayer from "xxxxx/xxx/xxx.vue"
	export default {
		data(){
			return{
				show: false
			}
		},
		components: {
			songPlayer 
		},
		onLoad(){
			console.log(this.$refs.songPlayer)// 會報 "songPlayer is undefined" 的問題
			this.$nextTick(()=>{
				console.log(this.$refs.songPlayer)
			})
			
		}
	}
</script>

內建元件指的是view這些,這個“坑坑”是由於這些元件不是vue元件,且和使用者的程式碼不在同一個環境中(不在邏輯層而在檢視層),獲取不到。

支付寶小程式中有點問題,但是可以改變方法獲取,具體請看:解決 uni-app 自定義元件在支付寶小程式中無法使用 ref 的問題