Javascript is required
Mokkapps LogoMichael Hoffmann

Vue Tip: Props and Context in Setup Method

Michael Hoffmann (Mokkapps) - Senior Frontend Developer (Freelancer)
Michael Hoffmann
Nov 13, 2021
1 min read
Vue Tip: Props and Context in Setup Method Image

The setup function in Vue 3 Composition API will take two arguments: props and context.

<script>export default {  props: {    title: String,  },  setup(props, context) {    /**     * Setup does not have the same access to `this` as     * the Options API methods.     * Thankfully, the setup method accepts a components props     * as its first argument     */    console.log(props)    /**     * Context object exposes three properties of a Vue instance     * 1. attrs - a component's attributes     * 2. slots - a component's slots     * 3. emit - allows us to emit an event from this component     */    console.log(context)    context.emit('eventName')  },}</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.


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:

export default {  setup(props, context) {    // Attributes (Non-reactive object, equivalent to $attrs)    console.log(context.attrs)    // Slots (Non-reactive object, equivalent to $slots)    console.log(context.slots)    // Emit events (Function, equivalent to $emit)    console.log(context.emit)    // Expose public properties (Function)    console.log(context.expose)  },}

If you liked this Vue tip, follow me on Twitter to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue newsletter.