Vue2路由的切换实质是 Vue 组件的销毁和创建,从一个组件切换到另外一个组件,类似于销毁一个组件再创建另外一个组件并挂载,而这里细节涉及到组件的创建,挂载,更新和销毁等生命周期钩子。
这里结合实例观察:
//App.vue 父组件 <template> <div id="app"> <nav> <router-link to="/" @click.native="showRoute">Home</router-link> | <router-link to="/about" @click.native="showRoute">About</router-link> </nav> <router-view /> </div> </template> <script> export default { name: 'App', methods: { } } } </script> // 子组件之一 <template> <div class="home"> <img alt="Vue logo" src="../assets/logo.png" /> <HelloWorld :msg="msg" /> <input type="text" v-model="new_value" /> <button @click="changMSG">改数值</button> </div> </template> <script> export default { name: 'HomeView', data () { return { msg: 'Hello Vue!', new_value: '' } }, methods: { changMSG () { this.msg = this.new_value } }, components: { // HelloWorld HelloWorld: () => import('@/components/HelloWorld.vue') }, beforeDestroy () { console.log('beforeDestroy HomeView') }, destroyed () { console.log('destroyed HomeView') }, beforeCreate () { console.log('beforeCreate HomeView') }, created () { console.log('Create HomeView') }, beforeMount () { console.log('beforeMount HomeView') }, mounted () { console.log('mounted HomeView') }, beforeUpdate () { console.log('beforeUpdate HomeView') }, updated () { console.log('updated HomeView') } } </script> // 另外一个子组件 <template> <div class="about"> <h1>This is an about page</h1> </div> </template> <script> export default { name: 'AboutView', beforeDestroy () { console.log('beforeDestroy AboutView') }, destroyed () { console.log('destroyed AboutView') }, beforeCreate () { console.log('beforeCreate AboutView') }, created () { console.log('Create AboutView') }, beforeMount () { console.log('beforeMount AboutView') }, mounted () { console.log('mounted AboutView') }, beforeUpdate () { console.log('beforeUpdate AboutView') }, updated () { console.log('updated AboutView') } } </script>
页面启动初结果:
当鼠标点击About页面的时候,控制台又输出:
可以看出,路由的切换近似于一个组件的销毁和另外一个组件的挂载。当然,旧组件被销毁之前要经历创建,挂载,更新等生命周期,新的组件也同样经历。大体上的阶段相似并且钩子是相近连续的,只不过在最后阶段,新组件在准备挂载和完成挂载期间执行的是旧组件最后的销毁阶段。
另外,当页面发生改变会触发update的相关生命周期钩子函数。