生命周期
组件声明周期的几个过程
- 创建
- 挂载
- 更新
- 销毁
创建
- beforeCreate (创建前)
初始化事件和生命周期后 - created (创建后)
相关数据注入时,这个时候可以获取到data中的值,但是无法获取DOM
挂载
- beforeMount (挂在前)
当data数据已经和vue模板渲染出HTML时,页面上还没有内容 - mounted (挂在后)
将编译好的HTML替换到页面上后,这个时候可以获取到真实的DOM
更新
- beforeUpdate (更新前)
当data中的值发生变化前,会触发该函数 - updated (更新后)
当data中值发生变化后,会触发该函数
销毁
- beforeDestroy (销毁前)
- destroyed (销毁后)
{
data () {
return {
}
},
methods: {
},
computed: {
},
生命周期钩子函数 () {
}
}
eg
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="app">
<h4 ref="strBox">{
{str}}</h4>
<my></my>
</div>
<script src="../js/vue.js"></script>
<script>
const my = {
template:
`
<div>hello woeld</div>
`,
methods: {
},
beforeCreate() {
console.log("beforeCreate" + "-------my1");
},
created() {
console.log("created" + "-------my2");
},
beforeMount() {
console.log("beforeMount" + "-------my3");
},
mounted() {
console.log("mounted" + "-------my4");
},
beforeUpdate() {
console.log("beforeUpdate" + "-------my5");
},
updated() {
console.log("updated" + "-------my6");
},
beforeDestroy() {
console.log("beforeDestroy" + "-------my7");
},
destroyed() {
console.log("beforeDestroy" + "-------my8");
},
}
Vue.component('my',my)
var vm = new Vue({
el: '#app',
data: {
str:'你是个麻瓜'
},
methods: {
},
// vue实例的挂载元素$el和数据对象data都为undefined,还未初始化。
// 加loading事件
beforeCreate() {
console.log("beforeCreate" + "-------app1");
},
// vue实例的数据对象data有了,$el还没有
// 结束loading、请求数据为mounted渲染做准备
created() {
console.log("created" + "-------app2");
},
// vue实例的$el和data都初始化了,但还是虚拟的dom节点,具体的data.filter还未替换。
beforeMount() {
console.log("beforeMount" + "-------app3");
},
// vue实例挂载完成,data.filter成功渲染
mounted() {
console.log("mounted" + "-------app4");
console.log(this.$refs.strBox);
},
// data更新时触发
beforeUpdate() {
console.log("beforeUpdate" + "-------app5");
this.$nextTick(() => {
console.log(this.$refs.strBox);
})
console.log(this.$refs.strBox);
},
// data更新时触发
updated() {
console.log("updated" + "-------app6");
},
// 组件销毁时触发
beforeDestroy() {
console.log("beforeDestroy" + "-------app7");
},
// 组件销毁时触发,vue实例解除了事件监听以及和dom的绑定(无响应了),但DOM节点依旧存在
destroyed() {
console.log("beforeDestroy" + "-------app8");
},
});
</script>
</body>
</html>