- 理解:Vue3.0中一个新的配置项,值为一个函数。
setup
是所有Composition API(组合API)“ 表演的舞台 ”。- 组件中所用到的:数据、方法等等,均要配置在
setup
中。 setup
函数的两种返回值:- 若返回一个对象,则对象中的属性、方法, 在模板中均可以直接使用。(重点关注!)
- 若返回一个渲染函数:则可以自定义渲染内容。(了解) (不常用)
- 尽量不要与Vue2.x配置混用
- Vue2.x配置(data、methos、computed...)中可以访问到setup中的属性、方法。
- 但在setup中不能访问到Vue2.x配置(data、methos、computed...)。
- 如果有重名,
setup
优先。
setup
不能是一个async
函数,因为返回值不再是对象, 而是promise
, 模板看不到return对象中的属性。(后期也可以返回一个Promise实例,但需要Suspense和异步组件的配合)
<template>
<h1>个人信息</h1>
<h2>姓名:{{ name }}</h2>
<h2>年龄:{{ age }}</h2>
<button @click="sayName">显示姓名</button>
<br />
<button @click="sayAge">显示年龄</button>
<br />
<button @click="test2">vue2的配置中去读取vue3的属性和方法</button>
<br />
<button @click="test3">vue3的配置中去读取vue2的属性和方法</button>
</template>
<script>
// import {h} from 'vue'
export default {
name: 'App',
data () {
return {
age: 24
}
},
methods: {
sayAge () {
alert(`我今年${this.age},本命年哦`)
},
test2 () {
console.log(this.age)
console.log(this.sayAge)
console.log(this.name) //vue2的配置中可以读取vue3的属性和方法
console.log(this.sayName)
}
},
//此处只是测试一下setup,暂时不考虑响应式的问题。
setup () {
// 数据
let name = '丫丫'
// 方法
function sayName () {
alert(`你好${name},你太厉害了吧`)
}
function test3 () {
console.log(name)
console.log(sayName)
console.log(this.age) //vue3的配置中读取不到vue2的属性和方法,显示undefined
console.log(this.sayAge)
}
return {
name,
sayName,
test3
}
// return ()=> h('h1','hi,美少女')
}
}
</script>
另外,需要注意的是:
- setup在beforeCreate钩子之前执行一次,此时的this是undefined
- setup的参数:
- props:值为对象,包含:组件外部传递过来,且组件内部声明接受了的属性
- context:
- attrs:值为对象,包含:组件外部传递过来,但没有在props配置中声明的属性,相当于this.$attrs
- slots:收到的插槽内容,相当于this.$slots
- emit:分发自定义事件的函数,相当于this.$emit