setup() 与 created()
老师视频中讲到 setup() 相当于 beforeCreate() 和 created() ,因此无法获取实例的data数据
但是根据生命周期图知道 created() 中数据已经进行了初始化, 可以获取data中的数据, 我也试了一下,确实可以, 但为什么setup() 不行
<template>
<p>get instance</p>
</template>
<script>
import { onMounted, getCurrentInstance, onBeforeMount } from "vue";
export default {
name: "GetInstance",
data() {
return {
x: 1,
y: 2,
};
},
setup() {
console.log("this1", this);
onBeforeMount(() => {
console.log("this in onBeforeMount", this);
console.log("x", instance.data.x);
});
onMounted(() => {
console.log("this in onMounted", this);
console.log("x", instance.data.x);
});
const instance = getCurrentInstance();
console.log("instance", instance);
},
created() {
console.log("x in created", this.x);
},
mounted() {
console.log("this2", this);
console.log("y", this.y);
},
};
</script>4
收起
正在回答
1回答
同学你好,严格来讲,setup是在beforeCreate之前执行的函数,可以测试一下:


数据是在created阶段才能获取,setup阶段比created早,所以获取不到data中的数据。
一般来说,简单记忆成“setup是beforeCreate、created的合集”就行了。极个别情况,可以通过打印,看看它们的实际执行顺序再写逻辑。
祝学习愉快!
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星