setup()函数使用细节
- setup 是一个新的组件选项,作为组件中使用组合API的起点。
- 从组件生命周期来看,它的执行在组件实例创建之前vue2.x的beforeCreate执行。
- 这就意味着在setup函数中 this 还不是组件实例,this 此时是 undefined
- 在模版中需要使用的数据和函数,需要在 setup 返回。
验证代码
<template><divid="app"></div></template><script>export default{
name:"App",setup(){
console.log("setup执行了");
console.log(this);},beforeCreate(){
console.log("beforeCreate执行了");
console.log(this);},};</script><style></style>
打印结果
可以看到 先执行了 setup 但是在setup中拿不到vue 实例对象也就是this
并且setup执行在beforcreate 之前 ,也就是说最早拿到vue 实例对象 是在beforecreate 钩子函数中
总结
setup 组件初始化之前执行,它返回的数据和函数可在模版使用。