- context对象中有三个参数
- attrs 用来替代 props:{} 来接受父组件的传值
- slots 函数时渲染父组件中的槽口内容
- emit 替代之前的 this.$emit 进行父子组件之间传值
用法如下
/*attrs*/
const app = Vue.createApp({
template:`
<child app="hello">parent</child>
`
});
app.component("child",{
setup(props,context){
const {attrs} = context;
console.log(attrs.app) // hello
}
})
const vm = app.mount('#root')
/*slots*/
const app = Vue.createApp({
template:`
<child>hello worlod</child>
`
})
app.component('child',{
setup(props,context){
const {h} = Vue;
const {slots} = context;
return ()=>h('div',{},slots.default())
}
})
/*emit*/
const app = createApp({
template:`
<child @xxx="parFun"></child>
`,
methods:{
parFun(params){
console.log("接收子组件传值",params)
}
}
})
app.component("child",()=>{
template:`
<div @click="test">child</div>
`,
setup(props,context){
const {attrs,slots,emit} = context;
const test = ()=>{
emit('xxx',666)
}
return {test}
}
})