npm install [email protected]
{
"name": "vue3-life",
"version": "0.0.0",
"scripts": {
"dev": "vite",
"build": "vite build"
},
"dependencies": {
"vue": "^3.2.0-beta.7",
"vue-router": "^4.0.0-beta.13"
},
"devDependencies": {
"vite": "^1.0.0-rc.13",
"@vue/compiler-sfc": "^3.0.4"
}
}
import { createRouter,createWebHashHistory} from "vue-router";
const routes = [
{
path: "/index1",
name: "index1",
component: () => import('/src/views/index1.vue')
},
{
path: "/index2",
name: "index2",
component: () => import('/src/views/index2.vue')
}
]
export default createRouter({
history:createWebHashHistory(),
routes:routes
})
import { createApp } from 'vue'
import App from './App.vue'
import './index.css'
//导入路由
import router from '/src/router/index'
createApp(App).use(router).mount('#app')
<template>
<button @click="toRouter('/index1')">index1路由</button>
<button @click="toRouter('/index2')">index2路由</button>
<router-view>
</router-view>
</template>
<script>
import HelloWorld from './components/HelloWorld.vue'
import {useRouter} from 'vue-router'
import {reactive,toRefs} from "vue";
export default {
name: 'App',
components: {
HelloWorld
},
setup(){
const router = useRouter()
let state = reactive({
toRouter(routerPath){
router.replace(routerPath)
}
})
return {
...toRefs(state)
}
}
}
</script>
<template>
<br>
<button @click="msg = 'mmssgg'">更改msg</button>
<h1>index2</h1>
{{msg}}
<p>---</p>
{{getDate()}}
</template>
<script>
import {reactive, toRefs,onBeforeMount,onMounted,onBeforeUnmount,onUnmounted,onBeforeUpdate,onUpdated} from 'vue'
export default {
name: "index2",
setup(){
console.log('---index2 setup---')
onBeforeMount(()=>{
console.log('---index2 onBeforeMount---')
})
onMounted(()=>{
console.log('---index2 onMounted---')
})
onBeforeUpdate(()=>{
console.log('---index2 onBeforeUpdate---')
})
onUpdated(()=>{
console.log('---index2 onUpdated---')
})
onBeforeUnmount(()=>{
console.log('---index2 onBeforeUnmount---')
})
onUnmounted(()=>{
console.log('---index2 onUnmounted---')
})
let state = reactive({
msg:"index2-msg",
getDate(){
return new Date()
}
})
return {
...toRefs(state)
}
}
}
</script>
<style scoped>
</style>
在从index1路由切换到index2时打印如下
给所有声明周期函数debugger观察
setup是执行最早的一个,此时页面无内容。
此时页面依然是没有用内容。然后执行完这个钩子函数,vue就会将setup返回的内容渲染到模板中去。
点击更新按钮
onBeforeUpdate在更新模板前回调,此时页面还未被重新渲染,然后调用click的回调方法。再执行onUpdated
切换到index1路由
先是执行了onBeforeUnmount,此时页面还未卸载,还是index2的模板内容。(下图所示)
紧接着执行了index2的onUnmounted,此时页面已经是index1的模板了。也就是在index2的onBeforeUnmount和onUnmounted之前,执行了index1的setup、onBeforeMounted、onMounted。
这些钩子函数本身并没有渲染页面的能力,当页面上需要展示某个组件时,是vue解析了该组件的模板数据,并将渲染好的模板放入页面,和这些钩子函数并没有关系,只不过vue会在渲染的各个时机去调用我们写好的钩子函数,来完成一些特定的功能。