test.vue
<template>
<view id="myView">
这是test组件{{num}}
</view>
</template>
<script>
export default {
name:"test",
data() {
return {
num: 3,
intId: null
};
},
// 实例初始化,但是此时数据并没有初始化
beforeCreate(){
console.log("实例已经初始化了")
console.log(this.num)
},
// 此时数据初始化,通常在这里面显示一些数据,初始化数据在这里面
created(){
console.log('created',this.num)
// 设置一个定时器,时间为一秒
this.intId= setInterval(()=>{
console.log('执行定时器')
},1000)
},
beforeMount() {
console.log('beforemount',document.getElementById('myView'))
},
// 操作Dom元素,推荐在这里面操作
// 挂在需要id,根据id获取Dom元素
mounted() {
console.log('beforemount',document.getElementById('myView'))
},
destroyed() {
console.log("组件销毁了")
// 通过变量销毁定时器
clearInterval(this.intId)
}
}
</script>
<style>
</style>
index.vue
<template>
<view class="content">
<!-- v-if 来判断显示还是不显示 -->
<test v-if="flag"></test>
<button type="primary" @click="checkTest">切换方法</button>
</view>
</template>
<script>
import test from '../../components/test.vue'
export default {
data() {
return {
title: 'Hello',
flag: true
}
},
onLoad(options) {
console.log("页面加载了",options)
},
onShow(){
console.log('页面显示了')
},
onReady(){
console.log('页面初次渲染完成了')
},
onHide(){
console.log("页面隐藏了")
},
methods: {
checkTest(){
this.flag= !this.flag;
}
},
// 注册组件
components:{
test
}
}
</script>
<style>
.content {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.logo {
height: 200rpx;
width: 200rpx;
margin-top: 200rpx;
margin-left: auto;
margin-right: auto;
margin-bottom: 50rpx;
}
.text-area {
display: flex;
justify-content: center;
}
.title {
font-size: 36rpx;
color: #8f8f94;
}
</style>

本文详细介绍了Vue.js中组件的生命周期钩子函数,包括beforeCreate、created、beforeMount、mounted等阶段的功能及应用场景,帮助开发者更好地理解和使用Vue.js。
737





