Web前端vue必做笔记之一:组件api-组件的生命周期
beforeCreate > 使用 setup()
create > 使用setup()
beforeMount > onBeforeMount
mounted > onMounted
beforeUpdate > onbeforeUpdate
updated > onUpdated
beforeUnmount > onBeforeUnmount
UNmounted > onUnmounted
<template>
<div>
<h1>{{title}}</h1>
</div>
</template>
<script>
import {ref,reactive, onMounted} from 'vue';
export default {
//想写created,那怎么写呢
//可以直接写在setup()里
//setup()运行的时间与created的时间一样
setup(){ //可以代替created 和beforeCreate
console.log('beforeCreate');
onMounted(()=>{
console.log("hello world");
})
}
}
</script>
现在我们来实现一个简单的功能,一刷新页面就显示内容
<template>
<div>
<h1>{{title}}</h1>
</div>
</template>
<script>
import {ref,reactive, onMounted} from 'vue';
export default {
setup(){
const list = [
"你好",
"亲爱的用户",
"很高兴遇见你"
]
const title = ref("")
onMounted(()=>{
console.log("hello world");
let i = 0;;
let t = setInterval(() => {
title.value = list[i]
i++;
if(i === 3){
clearInterval(t);
}
},500)
})
return { //暴露出来,不然调用不了
title
}
}
}
</script>