-
app是應用實例,vm是根組件實例
image.png
<div id="app">
<fieldset>
<legend>組件實例</legend>
{{ message }}
<button @click="change">Click</button>
</fieldset>
</div>
<script>
const App = {
data() {
return {
message: 'Hello Vue!!'
}
},
methods: {
change() {
console.log(this)
this.message += '!'
}
},
}
const app = Vue.createApp(App)
console.log(app)
const vm = app.mount('#app')
console.log(vm)
</script>
image.png
生命周期
- mounted: 這時實例已被掛載,數據會出現在頁面中,Vue.createApp({}).mount() 被新創建的 vm.$el 替換了;也就是說你可以通過vm.$el獲取到根DOM元素;
- beforeUpdate: 數據更新時調用,雖然這時內存中的數據被更新了,但是視圖中的數據還沒有更新;
問題
1、鉤子函數
- beforeCreate、created、beforeMount、mounted、beforeUpdate、updated、
beforeUnmount、unmounted - 與Vue2不同的是beforeDestroy、destroyed變成了beforeUnmount、unmounted
2、如果需要發送Ajax請求,最好放在哪個鉤子函數?
發送請求當然越早越好,而最早只能放在created鉤子里;因為在created時已經完成以下配置:數據檢測、屬性和方法的運算,watch和event回調;
3、??組件嵌套時,?組件視圖和?組件視圖渲染完成誰先誰后?
(注意問的是渲染完成的先后,即在視圖中出現的順序,不是父子組件聲明周期執行的順序啊喂!!!)
- 答:不確定。因為雖然根據父子生命周期執行順序來看,父組件mounted之前子組件就以mounted完成,但是子組件是在父組件里面的,父組件不出現,子組件也不可能出現,所以它倆誰先誰后并不確定;
4、父子組件的生命周期執行順序
加載渲染過程
父beforeCreate —> 父created —> 父beforeMount —> 子beforeCreate —> 子created —> 子beforeMount —> 子mounted —> 父mounted子組件更新過程
父beforeUpdate —> 子beforeUpdate —> 子updated —> 父updated父組件更新過程
父beforeUpdate —> 父updated銷毀過程
父beforeUnmount—> 子beforeUnmount—> 子unmounted—> 父unmounted
可以發現,子組件的生命周期都在父組件beforeXxx和xxxed之間去執行的
5、??組件嵌套時,如果希望在所有組件視圖都渲染完成后再執?操作,該如何做?
mounted() {
this.$nextTick(function () {
// 僅在渲染整個視圖之后運?的代碼
})
}