前端必知必会-Vue ‘created‘ 生命周期钩子

文章目录


‘created’ 钩子

created 生命周期钩子发生在组件初始化之后,因此 Vue 已经设置了组件的数据、计算属性、方法和事件监听器。

我们应该避免尝试从 created 生命周期钩子访问 DOM 元素,因为在组件挂载之前,DOM 元素是不可访问的。

created 生命周期钩子可用于通过 HTTP 请求获取数据,或设置初始数据值。如下例所示,数据属性“text”被赋予了初始值:

示例
CompOne.vue:

<template>
<h2>Component</h2>
<p>This is the component</p>
<p id="pResult">{{ text }></p>
</template>

<script>
export default {
data() {
return {
text: '...'
}
},
created() {
this.text = 'initial text';
console.log("created: The component just got created.");
}
}
</script>

App.vue:

<template>
<h1>'created' 生命周期钩子</h1>
<p>我们可以看到来自 'created' 生命周期钩子的 console.log() 消息,并且我们尝试对 Vue 数据属性进行的文本更改有效,因为 Vue 数据属性在此阶段已创建。</p>
<button @click="this.activeComp = !this.activeComp">添加/删除组件</button>
<div>
<comp-one v-if="activeComp"></comp-one>
</div>
</template>

<script>
export default {
data() {
return {
activeComp: false
}
}
}
</script>

<style>
#app > div {
  border: dashed black 1px;
  border-radius: 10px;
  padding: 10px;
  margin-top: 10px;
  background-color: lightgreen;
}
#pResult {
  background-color: lightcoral;
  display: inline-block;
}
</style>

总结

本文介绍了Vue ‘created’ 生命周期钩子的使用,如有问题欢迎私信和评论

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

编程岁月

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值