文章目录
‘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’ 生命周期钩子的使用,如有问题欢迎私信和评论