Two points of attention for setup
First of all, in v2, when the parent component passed parameters to the child component, we used props to receive them. Of course, in addition to this method, we can also receive them through $attr, but using $atter cannot pass parameters from the parent component. Parameters are limited by type, and it is more troublesome to get and use, and you need to use dot syntax
Note that one of the amazing things about this is that if you receive the data passed by it (put it in props), then it will not be in vc's $attr. Another point is that $slots, which is what we are
in When using slots, vue will put the slots in $slots
. After talking about the content before v2, let’s talk about
the timing of the setup execution of v3
. Execute once before Create, this is undefined.
We clearly see here today that the setup is executed earlier than beforeCreate, and its this is undefined, which will lead to, in the setup, you can’t use this. Its
first parameter is passed from the parent component to the child component And
it turns the data we passed into a proxy object, that is, it realizes the responsive function.
Its second parameter is the context object.
Here we use context.attrs. We found that we don’t have it in props The received value is here
and the context object is what we need
. Test the emit function
but this is incomplete. I also need to tell this component that you have bound this custom event, otherwise it will warn (of course , you can leave it alone, it can still be used normally)
context.slots is what puts the slot, one thing to note here is that in v3, if you want to give the slot a name, you'd better use v-slot :name, otherwise you use slot="name" which is incompatible
Summarize
- The timing of setup execution
- Executed once before beforeCreate, this is undefined.
- parameter of setup
- props: The value is an object, including: the properties passed from outside the component and received by the internal declaration of the component.
- context: context object
- attrs: The value is an object, including: attributes passed from outside the component but not declared in the props configuration, equivalent to
this.$attrs
. - slots: Received slot content, equivalent to
this.$slots
. - emit: A function that dispatches custom events, equivalent to
this.$emit
.
- attrs: The value is an object, including: attributes passed from outside the component but not declared in the props configuration, equivalent to