Mokkapps Logo

Vue Tip: Props and Context in Setup Method

Michael Hoffmann (Mokkapps) - Senior Frontend Developer (Freelancer)
November 13, 2021
1 Minuten Lesezeit
- Ansichten

When using the setup function in Vue 3 Composition API, it will take two arguments: props and context.

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

     * 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

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)

    // Slots (Non-reactive object, equivalent to $slots)

    // Emit events (Function, equivalent to $emit)

    // Expose public properties (Function)

If you liked this tip, follow me on Twitter to get notified about new tips, blog posts and more content from me.

Alternatively (or additionally), you can also subscribe to my newsletter.

Sie haben einen Fehler in diesem Artikel gefunden? Sie möchten gerne etwas klarstellen, aktualisieren oder hinzufügen?

Alle meine Artikel können auf Github editiert werden. Jeder Fix ist willkommen, egal wie klein er sein mag!

Ändern auf Github