Setup

    When using the function, it will take two arguments:

    1. props
    2. context

    Let’s dive deeper into how each argument can be used.

    The first argument in the setup function is the props argument. Just as you would expect in a standard component, props inside of a setup function are reactive and will be updated when new props are passed in.

    However, because props are reactive, you cannot use ES6 destructuring because it will remove props reactivity.

    If you need to destructure your props, you can do this safely by utilizing the toRefs inside of the setup function.

    1. // MyBook.vue
    2. import { toRefs } from 'vue'
    3. setup(props) {
    4. const { title } = toRefs(props)
    5. }

    Context

    The second argument passed to the setup function is the context. The context is a normal JavaScript object that exposes three component properties:

    Because it is a normal JavaScript object, i.e., it is not reactive, this means you can safely use ES6 destructuring on context.

    1. // MyBook.vue
    2. setup(props, { attrs, slots, emit }) {
    3. ...
    4. }
    5. }

    When setup is executed, the component instance has not been created yet. As a result, you will only be able to access the following properties:

    • props
    • attrs
    • slots
    • emit

    In other words, you will not have access to the following component options:

    • data
    • computed
    • methods

    If setup returns an object, the properties on the object can be accessed in the component’s template:

    1. <!-- MyBook.vue -->
    2. <template>
    3. </template>
    4. <script>
    5. import { ref, reactive } from 'vue'
    6. export default {
    7. setup() {
    8. const readersNumber = ref(0)
    9. const book = reactive({ title: 'Vue 3 Guide' })
    10. // expose to template
    11. return {
    12. readersNumber,
    13. book
    14. }
    15. }
    16. </script>

    Note that refs returned from setup are when accessed in the template so you shouldn’t use .value in templates.

    Inside setup(), this won’t be a reference to Vue instance Since setup() is called before other component options are resolved, this inside setup() will behave quite differently from this in other options. This might cause confusions when using along other Options API.