组合API-setup函数
作用
setup
是一个新的组件选项,作为组件中使用组合API的起点。
- setup 函数是一个新的组件选项,作为组件中组合式API 的起点(入口)
- setup 中不能使用 this, this 指向 undefined
- setup函数只会在组件初始化的时候执行一次
- setup函数在beforeCreate生命周期钩子执行之前执行
执行时机
执行在组件实例创建之前执行(在beforeCreate前)
setup() {
console.log('setup....', this)
},
beforeCreate() {
console.log('beforeCreate') // 它比setup迟
}
在setup
函数中 this
还不是组件实例,this
此时是 undefined
参数
// 第1个参数为props。props为一个对象,内部包含了父组件传递过来的所有prop数据
// 第2个参数为一个对象context。context对象包含了attrs,slots, emit属性,
setup(props, context) {
}
返回值
这个函数的返回值是一个对象,在模版中需要使用的数据和函数,需要在这个对象中声明。
如果在data()中也定义了同名的数据,则以setup()中为准。
演示代码
<template>
<div class="container">
姓名:{{name}},月薪:{{salary}} <button @click="say">打个招呼</button>
</div>
</template>
<script>
export default {
setup () {
console.log('setup执行了')
console.log(this)
// 定义数据和函数
const name = '小吴'
const salary = 18000
const say = () => {
console.log('我是', name)
}
return { msg , say}
},
beforeCreate() {
console.log('beforeCreate执行了')
console.log(this)
}
}
</script>
小结
- setup比beforeCreate先执行
- setup不能用this访问,它会返回undefined
- setup的返回值格式是对象