成都 網(wǎng)站建設(shè)培訓(xùn)semen
- vue3 如何使用 mounted
在 Vue 3 中,mounted 生命周期鉤子用于當(dāng)組件被掛載到 DOM 中后執(zhí)行一些操作。
這個(gè)鉤子非常適合用來執(zhí)行那些依賴于 DOM 的初始化工作,比如獲取元素的尺寸或者是與第三方的 DOM 有關(guān)的庫(kù)進(jìn)行交互等。
下面是一個(gè)簡(jiǎn)單的 Vue 3 組件示例,展示了如何使用 mounted 鉤子:
import { ref, onMounted } from 'vue'export default {setup() {const count = ref(0)// 在組件掛載完成后執(zhí)行onMounted(() => {console.log('Component is now mounted and ready')// 這里可以執(zhí)行任何需要在掛載完成后做的事情// 比如訪問真實(shí)的 DOM 元素const el = document.querySelector('#my-element')console.log(el)// 或者啟動(dòng)一個(gè)輪詢定時(shí)器const interval = setInterval(() => {count.value++}, 1000)// 清理函數(shù),在組件卸載前清除定時(shí)器return () => {clearInterval(interval)}})return { count }}
}
在這個(gè)例子中,onMounted 接受一個(gè)函數(shù)作為參數(shù),該函數(shù)會(huì)在組件掛載到 DOM 后立即執(zhí)行。
這里也展示了如何在 onMounted 回調(diào)中返回一個(gè)清理函數(shù),它會(huì)在組件卸載時(shí)被調(diào)用,這對(duì)于清除副作用(如定時(shí)器)非常有用。
注意,Vue 3 使用了 Composition API,因此傳統(tǒng)的選項(xiàng)式寫法中的生命周期鉤子(如 mounted)已經(jīng)被 setup() 函數(shù)中的 onMounted() 函數(shù)所替代。
如果你是從 Vue 2 升級(jí)到 Vue 3,這可能是需要注意的一個(gè)變化。
- vue3 mounted 的觸發(fā)時(shí)機(jī)
在 Vue 3 中,mounted 生命周期鉤子的觸發(fā)時(shí)機(jī)是在組件實(shí)例被掛載到 DOM 后。
具體來說,這意味著以下幾點(diǎn):
- 實(shí)例創(chuàng)建完成:Vue 實(shí)例已經(jīng)完成了數(shù)據(jù)觀測(cè)(data observer)、屬性和方法的運(yùn)算,以及指令配置。此時(shí),數(shù)據(jù)模型已經(jīng)可以正常工作,但尚未開始第一次 DOM 渲染。
- DOM 掛載完成:Vue 實(shí)例已經(jīng)完成了模板編譯和渲染,并且組件已經(jīng)被插入到父容器節(jié)點(diǎn)中,DOM 已經(jīng)被更新以反映組件的初始狀態(tài)。
- $el 屬性可用 :組件的 e l 屬性已經(jīng)被創(chuàng)建并且可以訪問,這意味著你可以在這個(gè)階段通過 t h i s . el 屬性已經(jīng)被創(chuàng)建并且可以訪問,這意味著你可以在這個(gè)階段通過 this. el屬性已經(jīng)被創(chuàng)建并且可以訪問,這意味著你可以在這個(gè)階段通過this.el 訪問到掛載后的 DOM 節(jié)點(diǎn)。
- ref 屬性可用:所有注冊(cè)過的 ref 屬性都已經(jīng)解析,并且可以通過 this.$refs 訪問到它們引用的 DOM 元素或子組件實(shí)例。
簡(jiǎn)而言之,mounted 鉤子是當(dāng)你需要在組件掛載后執(zhí)行一些操作時(shí)使用的理想位置,比如:
- 操作 DOM:由于組件已經(jīng)掛載到了 DOM 中,你現(xiàn)在可以安全地查詢或操作 DOM。
- 初始化第三方插件:很多第三方插件或庫(kù)需要一個(gè)已經(jīng)存在的 DOM 節(jié)點(diǎn)來初始化,mounted 是一個(gè)合適的時(shí)間點(diǎn)。
- 發(fā)送網(wǎng)絡(luò)請(qǐng)求:如果需要在組件加載時(shí)獲取數(shù)據(jù),可以在 mounted 鉤子中發(fā)起網(wǎng)絡(luò)請(qǐng)求。
- 設(shè)置定時(shí)器:如果需要在組件掛載后定期執(zhí)行某些操作,可以在 mounted 鉤子中設(shè)置定時(shí)器。
import { ref, onMounted } from 'vue';export default {setup() {const message = ref('Hello, Vue 3!');onMounted(() => {console.log('Component has been mounted!');// 在這里可以安全地操作 DOMconst element = document.getElementById('app');console.log(element); // 輸出掛載后的 DOM 節(jié)點(diǎn)// 發(fā)送網(wǎng)絡(luò)請(qǐng)求fetch('https://api.example.com/data').then(response => response.json()).then(data => {console.log('Fetched data:', data);message.value = data.message; // 更新組件的狀態(tài)}).catch(error => {console.error('Error fetching data:', error);});});return { message };}
};
在這個(gè)示例中,當(dāng)組件掛載到 DOM 后,控制臺(tái)會(huì)打印一條消息,表示組件已經(jīng)掛載。
此外,還會(huì)發(fā)起一個(gè)網(wǎng)絡(luò)請(qǐng)求來獲取數(shù)據(jù),并更新組件的狀態(tài)。這些都是在 mounted 鉤子中常見的操作。