Vue3 setup的两个注意点
一、执行时机
在beforeCreate之前执行一次,this是undefined。
<script>
import Demo from './components/Demo.vue'
export default {name: 'App',components:{Demo},mounted() {console.log('-------mounted----------') //后输出},setup() {console.log('--------setup----------') //先输出}
}
</script>
二、参数
1.props:值为对象,包含:组件外部传递过来,且组件内部声明接收了的属性。
2.context:上下文对象
(1).attrs:值为对象,包含:组件外部传递过来,但没有在props配置中声明的属性,相当于 this.$attrs 。
(2).emit:分发自定义事件的函数, 相当于 this.$emit
。
(3).slots:收到的插槽内容, 相当于 this.$slots
。
<template><h1>一个人的信息</h1><slot name="Hello"></slot><h2>姓名:{{ name }}</h2><h2>年龄:{{ age }}</h2><button @click="sendNameBtn">发送姓名</button><br /><br />
</template><script>
export default {name: "Demo",props:['name','age'],emits:['sendName'],setup(props,context) {// console.log(props)// console.log('@@@@',context)// console.log('@@@@',context.attrs['age']) //相当于vue2中的$attrs// console.log('@@@@',context.emit) //相当于vue2中的$emit,用于触发自定义事件console.log('@@@@',context.slots) //插槽function sendNameBtn(){context.emit('sendName',props.name)}return {sendNameBtn};},
};
</script>
注意:在Vue3中具名插槽只能使用在template上。
<template v-slot:Hello>
<h1>你好啊!</h1>
</template>