Vue Tip: Props and Context in Setup Method
The setup function in Vue 3 Composition API will take two arguments: props
and context
.
1<script>
2export default {
3 props: {
4 title: String,
5 },
6 setup(props, context) {
7 /**
8 * Setup does not have the same access to `this` as
9 * the Options API methods.
10 * Thankfully, the setup method accepts a components props
11 * as its first argument
12 */
13 console.log(props)
14
15 /**
16 * Context object exposes three properties of a Vue instance
17 * 1. attrs - a component's attributes
18 * 2. slots - a component's slots
19 * 3. emit - allows us to emit an event from this component
20 */
21 console.log(context)
22 context.emit('eventName')
23 },
24}
25</script>
The first argument in the setup
function is the props
argument. props
are reactive and will be updated when new props are passed in.
Warning
You cannot use ES6 destructuring because it will remove props
reactivity. If you want to destructure props
you need to use toRefs.
The second argument in the setup
function is the context
argument. It is a normal JavaScript object that exposes some useful values:
1export default {
2 setup(props, context) {
3 // Attributes (Non-reactive object, equivalent to $attrs)
4 console.log(context.attrs)
5
6 // Slots (Non-reactive object, equivalent to $slots)
7 console.log(context.slots)
8
9 // Emit events (Function, equivalent to $emit)
10 console.log(context.emit)
11
12 // Expose public properties (Function)
13 console.log(context.expose)
14 },
15}
If you liked this Vue tip, follow me on X to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter:
Vue Tip: Detailed Prop Definitions
Define your Vue prop definitions as detailed as possible.
Vue Tip: Avoid Empty Class Attributes
This Vue tip helps to avoid empty class attributes in the rendered HTML