常用的生命周期钩子:
- mounted: 发送ajax请求、启动定时器、绑定自定义事件、订阅消息等【初始化操作】。
- beforeDestroy: 清除定时器、解绑自定义事件、取消订阅消息等【收尾工作】。
关于销毁Vue实例
- 销毁后借助Vue开发者工具看不到任何信息。
- 销毁后自定义事件会失效,但原生DOM事件依然有效。
一般不会在beforeDestroy操作数据,因为即便操作数据,也不会再触发更新流程了。
代码解析
<body><div id="app"><h1 :class="redBG">{{msg}}</h1><hello-com v-if='isShow'></hello-com></div><script>let helloCom = Vue.component('hello-com', {template: '<h1>{{msg}}</h1>',data: function() {return {msg: 'AAA'}},beforeDestroy() {//应用销毁之前//此时还能访问到实例的组件和方法console.log('beforeDestroy')console.log(this.msg) //AAA},destroyed() {//应用销毁之后//此时还能访问到实例的组件和方法//不要在这里操作数据和方法console.log('destroyed')console.log(this.msg)}})let app = new Vue({el: "#app",data: {msg: "Hellow",redBG: "redBG",isShow: true //控制组件销毁},methods: {clickEvent() {}},comments: {'hello-com': helloCom},beforeCreate() {//Vue实例刚被创建 数据/事件都还没更新console.log(this) //Vueconsole.log(this.msg) //undefinedconsole.log(this.clickEvent) //undefined},created() {//数据data和方法methods绑定到应用对象app上(还未渲染到视图)console.log(this.msg) //Hellowconsole.log(this.clickEvent) //fun},beforeMount() {//渲染之前,根据数据生成Domlet dom = document.querySelector(".redBG")console.log(dom) //null},mounted() {//渲染之后,可以获取数据生成的Dom对象let dom = document.querySelector(".redBG")console.log(dom) // </h1>},beforeUpdate() {//数据更改但内容未更改let dom = document.querySelector(".redBG")console.log(dom.innerHTML)},updated() {//内容更改完毕let dom = document.querySelector(".redBG")console.log(dom.innerHTML)}})</script></body>
