Vue – Why setup with reactive when you can do it easily with data option?

I am currently building a login for a Vue app. In a tutorial (02/2021) I see that the colleague creates a setup method and imports a Vue reactive object into the component. Just to collect the form data! Can’t this just be done with the data method?

HTML / Login Component

<template>
  <form action="/action_page.php" method="post">
    <div class="container">
      <input v-model="data.username" type="text" placeholder="Enter Username" name="username" required />
      <input v-model="data.password" type="password" placeholder="Enter Password" name="password" required />
      <button type="submit">Login</button>
      {{ data }}
    </div>

  </form>
</template>

1. New variant of databinding? Is that really necessary?

import {reactive} from 'vue';

export default {
    name: 'Login',
    setup() {
        const data = reactive({
            email: '',
            username: ''
        })

        return {
            data
        }
    }
}

2. Old and easy variant

export default {
    name: 'Login',
    data() {
        return {
            data: {
                email: '',
                username: ''
            },
            
        }
    },
}

>Solution :

data field is an option in Options API where you can declare reactive data that can be used directly inside template or accessed in other hooks using this where everything in this API is organized by option data, methods, computed … and the component features are overlapped, but in Composition API the code is organized by feature that can be extracted and reused across many logics and components.

In Vue 3 the options API is still supported, but it’s recommended to use the composition one especially with script setup :

<script setup>
import {reactive} from 'vue';//can be auto imported in Nuxt or using auto import plugin in Vue SPA

const data = reactive({
            email: '',
            username: ''
        })
</script>
  

Leave a Reply