The Vue3 release not only changes the way the underlying response to data is implemented, but also introduces a new Composition API, bringing a different development experience.

Although some say the composite API is copied from the React Hooks. But in the open source world, there is no such thing as copying. Who is better, solves more problems, and has a better development experience.

From vue3’s combinatorial API to the earlier React hooks, everyone seems to be moving in a direction that could be a new wave of front-end development. What is that wave? It’s called functional programming.

I don’t express my views on functional programming here, but as a small front-end developer, I can only be a person who goes with the flow without being able to change the tide.

1. Simple needs

The requirement of this time is very simple, is to achieve a registration form, the user input user name, mobile phone number, password, confirm password, click register to print out the information that the user fills in.

Let’s take a look at four different styles of coding using different technology stacks.

Two, using VUe2 implementation

// RegisterForm.vue

<template>
  <form class="reg-form" @submit.prevent="handleRegister">
    <div class="reg-form-item">
      <div>User name:</div>
      <input
        type="text"
        :value="formData.userName"
        @change="handleUserChange('userName', $event)"
        placeholder="Please enter user name"
      />
    </div>
    <div class="reg-form-item">
      <div>Mobile phone no. :</div>
      <input
        type="text"
        :value="formData.userPhone"
        @change="handleUserChange('userPhone', $event)"
        placeholder="Please enter your mobile phone number."
      />
    </div>
    <div class="reg-form-item">
      <div>Password:</div>
      <input
        type="password"
        :value="formData.userPassword"
        @change="handleUserChange('passwordAgain', $event)"
        placeholder="Please enter your password"
      />
    </div>
    <div class="reg-form-item">
      <div>Confirm password:</div>
      <input
        type="password"
        :value="formData.passwordAgain"
        @change="handleUserChange('userPassword', $event)"
        placeholder="Please enter your password confirmation."
      />
    </div>
    <div class="reg-btn">
      <button>Confirm the registration</button>
    </div>
  </form>
</template>

<script>
export default {
  data() {
    return {
      formData: {
        userName: "".userPhone: "".userPassword: "".passwordAgain: "",}}; },methods: {
    // Handle registration events
    handleRegister() {
      console.log(
        'User name:The ${this.formData.userName}, Mobile phone Number:The ${this.formData.userPhone}And password:The ${this.formData.userPassword}. `
      );
    },

    // Handle user data collection
    handleUserChange(type, e) {
      if (type in this.formData) {
        this.formData[type] = e.target.value; ,}}}};</script>

<style scoped>
.reg-form {
  width: 300px;
  padding: 20px;
  margin: 20px;
  border: 1px solid #ddd;
}
.reg-form-item {
  display: flex;
  padding: 5px 0;
}
.reg-form-item > div {
  width: 80px;
  line-height: 30px;
  text-align: right;
}
.reg-form-item > input {
  padding: 5px;
  width: 200px;
}
.reg-btn {
  text-align: center;
  margin-top: 20px;
}
.reg-btn button {
  width: 90%;
}
</style>


Copy the code

Technical Summary:

1. Vue2 is adoptedA three-stage(Template, Script, style tags) to achieve the development experience of one component per page.

2, use,v-bind(:value) Bind data,v-onBind events (@change).

3. If the event callback method requires passing parameters, the event will be lost, which Vue provides for us$eventParameter to get the event.

4,preventIs an event modifier that prevents the event from default behavior, equivalentevent.preventDefault().

In fact, the above example adopts the way of one-way data flow to achieve, vUE can actually make two-way data binding to the form, only need to use v-Model.

<template>
  <form class="reg-form" @submit.prevent="handleRegister">
    <div class="reg-form-item">
      <div>User name:</div>
      <input
        type="text"
        v-model="formData.userName"
        placeholder="Please enter user name"
      />
    </div>
    <div class="reg-form-item">
      <div>Mobile phone no. :</div>
      <input
        type="text"
        v-model="formData.userPhone"
        placeholder="Please enter your mobile phone number."
      />
    </div>
    <div class="reg-form-item">
      <div>Password:</div>
      <input
        type="password"
        v-model="formData.userPassword"
        placeholder="Please enter your password"
      />
    </div>
    <div class="reg-form-item">
      <div>Confirm password:</div>
      <input
        type="password"
        v-model="formData.passwordAgain"
        placeholder="Please enter your password confirmation."
      />
    </div>
    <div class="reg-btn">
      <button>Confirm the registration</button>
    </div>
  </form>
</template>

<script>
export default {
  data() {
    return {
      formData: {
        userName: "".userPhone: "".userPassword: "".passwordAgain: "",}}; },methods: {
    // Handle registration events
    handleRegister() {
      console.log(
        'User name:The ${this.formData.userName}, Mobile phone Number:The ${this.formData.userPhone}And password:The ${this.formData.userPassword}. `); ,}}};</script>

<style scoped>/ /... omit</style>
Copy the code

Three, using VUe3 implementation

<script setup>
// Composite API
import { reactive } from "vue";

const formData = reactive({
  userName: "".userPhone: "".userPassword: "".passwordAgain: ""});// Handle registration events
const handleRegister = () = > {
  console.log(
    'User name:${formData.userName}, Mobile phone Number:${formData.userPhone}And password:${formData.userPassword}. `
  );
};

</script>

<template>
  <form class="reg-form" @submit.prevent="handleRegister">
    <div class="reg-form-item">
      <div>User name:</div>
      <input
        type="text"
        v-model="formData.userName"
        placeholder="Please enter user name"
      />
    </div>
    <div class="reg-form-item">
      <div>Mobile phone no. :</div>
      <input
        type="text"
        v-model="formData.userPhone"
        placeholder="Please enter your mobile phone number."
      />
    </div>
    <div class="reg-form-item">
      <div>Password:</div>
      <input
        type="password"
        v-model="formData.userPassword"
        placeholder="Please enter your password"
      />
    </div>
    <div class="reg-form-item">
      <div>Confirm password:</div>
      <input
        type="password"
        v-model="formData.passwordAgain"
        placeholder="Please enter your password confirmation."
      />
    </div>
    <div class="reg-btn">
      <button>Confirm the registration</button>
    </div>
  </form>
</template>

<style scoped>/ /... omit</style>

Copy the code

Technical Summary:

1. Vue3 continues the three-stage development style of VUE2 with new additions<script setup>Tag, which makes it easy to write setup functions and use variables without a return.

2,reactiveThe function can define oneObject typeIs responsive data.

Note: For knowledge about VUe3, please refer to “VuE3 Development and Use Experience, to a technical summary”.

4. Use react class components

import React, { Component } from 'react'

export default class RegisterForm extends Component {
    state = {
        formData: {
            userName: "".userPhone: "".userPassword: "".passwordAgain: ""}}// Handle registration events
    handleRegister = (e) = > {
        e.preventDefault();
        const { formData: { userName, userPhone, userPassword } } = this.state;

        console.log(
            'User name:${userName}, Mobile phone Number:${userPhone}And password:${userPassword}. `
        );
    }
    
    // Handle user data collection
    handleUserChange = (type) = > {
        return (e) = > {
            if (type in this.state.formData) {
                this.setState(({ formData }) = > ({
                    formData: {
                        ...formData,
                        [type]: e.target.value
                    }
                }))
            }
        }
    }

    render() {
        const { formData: { userName, userPhone, userPassword, passwordAgain } } = this.state;

        return (
            <form className="reg-form" onSubmit={this.handleRegister} >
                <div className="reg-form-item">
                    <div>User name:</div>
                    <input
                        type="text"
                        value={userName}
                        onChange={this.handleUserChange('userName')}
                        placeholder="Please enter user name"
                    />
                </div>
                <div className="reg-form-item">
                    <div>Mobile phone no. :</div>
                    <input
                        type="text"
                        value={userPhone}
                        onChange={this.handleUserChange('userPhone')}
                        placeholder="Please enter your mobile phone number."
                    />
                </div>
                <div className="reg-form-item">
                    <div>Password:</div>
                    <input
                        type="password"
                        value={userPassword}
                        onChange={this.handleUserChange('userPassword')}
                        placeholder="Please enter your password"
                    />
                </div>
                <div className="reg-form-item">
                    <div>Password:</div>
                    <input
                        type="password"
                        value={passwordAgain}
                        onChange={this.handleUserChange('passwordAgain')}
                        placeholder="Please enter your password confirmation."
                    />
                </div>
                <div className="reg-btn">
                    <button>Confirm the registration</button>
                </div>
            </form>)}}Copy the code

Technical Summary:

1. Write react class components that need inheritanceReact.ComponentHTML can be usedjsxGrammar is written in therenderFunction to render.

2. Use it in form itemsstateManagement will becomeThe controlled components(value = {userName}).

React handles callback events with special carethisHandleRegister = (e) => {… }).

This.state. userName = ‘new name’; this.state.userName = ‘new name’this.setState()Function. To re-render the new DOM.

React does not have the event modifier in Vue and needs to handle the nativeThe event bubbling,Event default behaviorEtc. (e.preventdefault ()).

If you want to pass a parameter to a callback function that handles an event, the event will be lostHigher-order functions,Currization functionCan solve this problem.

handleUserChange = (type) = > {
        // The way this function returns a function is called a higher-order function
        // Fun (a)(b) This encoding method of taking multiple arguments instead of a single argument, and finally processing the arguments uniformly and returning them is called a Currization function.
        return (e) = > {
            // ...}}Copy the code

Use react functional components

import React, { useState } from 'react'

export default() = > {const [formData, setFormData] = useState({ // Use useState Hooks
        userName: ' '.userPhone: ' '.userPassword: ' '.passwordAgain: ' '
    })
    const { userName, userPhone, userPassword } = formData;
    const handleRegister = (e) = > {
        e.preventDefault();
        console.log(
            'User name:${userName}, Mobile phone Number:${userPhone}And password:${userPassword}. `
        );
    }

    // Handle user data collection
    const handleUserChange = (type) = > {
        return (e) = > {
            if (type informData) { setFormData({ ... formData, [type]: e.target.value }) } } }return (
        <form className="reg-form" onSubmit={handleRegister} >
            <div className="reg-form-item">
                <div>User name:</div>
                <input
                    type="text"
                    value={userName}
                    onChange={handleUserChange('userName')}
                    placeholder="Please enter user name"
                />
            </div>
            <div className="reg-form-item">
                <div>Mobile phone no. :</div>
                <input
                    type="text"
                    value={userPhone}
                    onChange={handleUserChange('userPhone')}
                    placeholder="Please enter your mobile phone number."
                />
            </div>
            <div className="reg-form-item">
                <div>Password:</div>
                <input
                    type="password"
                    value={userPassword}
                    onChange={handleUserChange('userPassword')}
                    placeholder="Please enter your password"
                />
            </div>
            <div className="reg-form-item">
                <div>Password:</div>
                <input
                    type="password"
                    value={passwordAgain}
                    onChange={this.handleUserChange('passwordAgain')}
                     placeholder="Please enter your password confirmation."
                />
            </div>     
            <div className="reg-btn">
                <button>Confirm the registration</button>
            </div>
        </form>)}Copy the code

Technical Summary:

1.HooksThis allows us to use the state of a class component, life hooks, and so on in a function component.

2,useState()Functions can do state management, among other thingsuseEffect()(Management life cycle),useRef()(handle interaction with the DOM). Specific reference towebsite

Six, summarized

The knowledge system related to VUE and React is very large, so I won’t elaborate on it due to space limitation. I just want to use the simple example above as a primer to let you experience different styles of development in different technology stacks.

There’s no easy way to compare vue and React because they focus on different things:

Vue, a lot of API design is out of the box. We only need to know how to use, can quickly and easily achieve the function. This is related to the design idea of the framework, VUE is a kind of progressive JS framework, step by step from easy to difficult, let you quickly start, spread is a kind of easy-to-use ideas.

React focuses on building easy-to-use UI component interfaces that provide a development experience closer to native JS. This is an advantage that allows component design to be more flexible and efficient.

So vue and React are not superior to each other, they are both excellent frameworks and libraries for the front-end ecosystem. Of course, we’re not taking a choice question, one of two. As a qualified front end engineer, the best solution is to have both.