vuejs的極大程度的幫助減少了對dom的操作,他主要通過添加ref屬性,但是當獲取this.$refs屬性時,稍有不注意就會輸出undefined導致我們對dom節點的操作報錯。
this.$refs.xxx為undefined的幾種情況記錄:
1、在created里鈎子函數中調用
原因:created()在實例創建完成后被立即調用。在這一步,實例已完成以下的配置:數據觀測 (data observer),屬性和方法的運算,watch/event 事件回調。然而,掛載階段還沒開始,$el
屬性目前不可見。所以this.$refs壓根就調不到那個dom,因為頁面還沒有掛載上去。
解決:在mounted () 鈎子函數中調用
注意:在此種情況中,元素節點一定是直接寫在html中的,而不是通過數據或者條件渲染的
2、數據或條件渲染(v-if,v-show)之后的調用
原因:
/** ref
本身作為渲染結果被創建,在初始渲染的時候不能訪問他們,是不存在的
$refs不是響應式的,只在組件渲染完成后才填充
用於元素或子組件注冊引用信息,注冊完成,將會注冊在父組件$refs對象上
調用對象是否和v-if結合使用
ref不是響應式的,所有的動態加載的模板更新它都無法相應的變化。
*/
解決:可以通過setTimeOut(()=>{...}, 0)來實現
代碼說明:
<template> <div> <p ref="testText">this is a test data</p> <p v-if="msg" ref="msgText">{{msg}}</p> <button @click="handleClick">點一下</button> </div> </template> <script> import { setTimeout } from 'timers'; export default { data () { return { text: 'message show', msg: '' } }, created () { console.log(this.$refs.testText) // undefined // this.$refs.testText.style.color = '#f00' }, mounted () { console.log(this.$refs.testText) // <p data-v-5752faac="" style="color: rgb(255, 0, 0);">this is a test data</p> console.log(this.$refs.msgText) // undefined this.$refs.testText.style.color = '#f00' }, methods: { handleClick () { this.msg = 'msg show' console.log(this.$refs.msgText) // undefined setTimeout(() => { this.$refs.msgText.style.color = '#eee' console.log(this.$refs.msgText) // <p data-v-5752faac="" style="color: rgb(238, 238, 238);">msg show</p> }, 0) } } }