Last week I wrote a React tutorial for Vue users. You deserve it. This is the second in a series of articles. On September 18 this year, the 89th anniversary of the 918 Incident, Vue3.0 was officially released. I believe that many of you have read Vue3.0 related articles. Today, this article will compare and contrast the usage of Vue2,Vue3 and React.
datadata
In thereact
In the callstate
People who are familiar with VUE will not be unfamiliar with data in VUE. Anyway, they need to use data every day when writing bugs. However, data is used differently in Vue2.0,Vue3.0 and React
Vue2.0
The usage
The following code is a relatively simple use of data for Vue2.0
<template>
<div>{{ name }}</div>
</template>
<script>
export default {
data() {
return {
name: 'zijun'.gzh: 'Front end has play'}}}</script>
Copy the code
The above code shows that data is a function, and the function returns an object. So why is data a function? For example, we sometimes see data not being a function in app.vue files.
<template>
<div id="app">
<router-view />
</div>
</template>
<script>
export default {
data: {name: 'zijun'.sex: 'male'}}</script>
Copy the code
So why do we declare data as a function in a normal component? When a component is defined, data must be declared as a function that returns an initial data object, since the component may be used to create multiple instances. If data were still a pure object, all instances would share references to the same data object! By providing the data function, each time a new instance is created, we can call the data function to return a new copy of the original data.
App.vue can declare data as a common object because app. vue is only used once in the whole system, so there is no such problem.
Vue3
The usage
In Vue3, we can still use data in the same way as in Vue2. Of course, Vue3 provides a new Composition API, and in future articles, we will refer to the Composition API by default unless otherwise specified.
The Composition API provides reactive apis, ref and Reactive, through which reactive data is generated
Basic usage
<template>
<div class="home">
<div>Name :{{state.name}}</div>
<div>Public id :{{state.gzh}}</div>
<div>Statistics :{{count}}</div>
</div>
</template>
<script lang="ts">
import { defineComponent, reactive, ref } from "vue";
export default defineComponent({
name: "Home".setup() {
const state = reactive({
name: "Zijun".gzh: "There's play on the front end."
});
const count = ref(0);
return{ state, count }; }});</script>
Copy the code
Response data modification
In Vue2.0, we normally modify data using the this.name = ‘zhang SAN’ assignment, but the Composition API provides two apis, so the usage is slightly different
<template>
<div class="home" @click="handleClick">
<div>Name :{{state.name}}</div>
<div>Public id :{{state.gzh}}</div>
<div>Statistics :{{count}}</div>
</div>
</template>
<script lang="ts">
import { defineComponent, reactive, ref } from "vue";
export default defineComponent({
setup() {
const state = reactive({
name: "Zijun".gzh: "There's play on the front end."
});
const count = ref(0);
function handleClick() {
state.name = "Zhang";
count.value++;
}
return{ state, count, handleClick }; }});</script>
Copy the code
As shown in the code above:
-
Data declared for Reactive
In reactive, we can fetch data by state.name and then modify data by state.name=’ chang ‘
-
For ref declared data
For the data declared by ref, ref takes a parameter value and returns a responsive and mutable REF object. The ref object has a single.value attribute that points to an internal value. So we need to use count.value to get the ref object in our code, and we also need to use count.value++ to change the value.
:{{count}}:{{count}} Vue itself will unpack it to count.value.
React
The usage
Act16.8 added the Hook feature, which is now widely used by many teams, so this article focuses more on hooks.
Vue3.0 provides the Composition API, which is similar to the React hook usage. Next, we will change the Vue3.0 code to the React version
import React, { useState } from 'react'
export default function() {
// useState passes in the state data to initialize and returns an array
// The first item of the array is the declared data, and the second argument is a method to call
// Modify the data
const [name, setName] = useState('zijun')
const [gzh] = useState('Front end has play')
function handleClick() {
// Modify data in React by calling the method returned by useState
setName('Joe')}return (
<div onClick={handleClick}>
<div>Name: {name}</div>
<div>Public id: {GZH}</div>
</div>
);
}
Copy the code
In this code we declare a state variable using useState, useState returns an array, and then we get two variables by deconstructing the array, Const [name, setName] = useState(‘ subjun ‘), where name corresponds to the declared state variable, and setName is a function to modify the value of the variable, such as setName(‘ chang SAN ‘), At that point, the value of name will change to triple
The listenerwatch
There’s nothing wrong with supervising you
Xiaobian often uses Watch in daily development. Watch can be used to monitor changes in data and then perform a series of operations after the changes. For example, if we have a list page, we want the search to be triggered automatically when the user enters a search term. In addition to listening for input events in the input box, you can also listen for keyword changes through vue’s Watch
Vue2.0
In the writing
In VUe2.0, there are two commonly used writing methods for Watch. We will use different writing methods to realize the above functions
-
Conventional implementation
<template> <div> <div> <span>search</span> <input v-model="searchValue" /> </div> <! -- list, code omitted --> </div> </template> <script> export default { data() { return { searchValue: ' '}},watch: { // Reload the data after the value changes searchValue(newValue, oldValue) { // Judge the search if(newValue ! == oldValue) {// Handle the search logic here}}}}</script> Copy the code
-
Use the $watch implementation
<template> <div> <div> <span>search</span> <input v-model="searchValue" /> </div> <! -- list, code omitted --> </div> </template> <script> export default { data() { return { searchValue: ' '}},created() { // $watch returns an unwatch function. If you need to cancel watch in certain scenarios, you can execute 'unwatch' const unwatch = this.$watch('searchValue'.(newValue, oldValue) = > { // Judge the search if(newValue ! == oldValue) {// Handle the search logic here}}}})</script> Copy the code
When calling $watch, there will be a return value unwatch. Then, if we need to cancel watch listening, we can call unwatch to do so. For example, there is a form, the save button on the form is usually gray, but if the user changes the form, You need to change the greying state of the form to enable. However, if the form is already enabled, there is no need to continue watch, so use unwatch instead
Vue3.0
In the writing
In addition to the writing method in Vue2.0, Vue3.0 also provides watch and watchEffect apis in Composition API, which are used to monitor changes of data. Below, we will use Watch and watchEffect respectively to realize the above search
watch
implementation
<template>
<div>
<span>search</span>
<input v-model="state.searchValue" />
</div>
</template>
<script lang="ts">
import { defineComponent, reactive, watch } from "vue";
export default defineComponent({
setup() {
const state = reactive({
searchValue: ""
});
// Use watch to listen for changes to the searchValue
const unwatch = watch(
() = > state.searchValue,
(value, oldValue) = > {
if(value ! == oldValue) {// Handle the search logic here}});return{ state }; }});</script>
Copy the code
The watch API is basically consistent with the usage of this.$watch in Vue2.0, including the parameters used, etc. Meanwhile, the Watch API returns the unwatch function to cancel the watch
Watch can also listen for changes to multiple properties, as shown below
watch([a,b,c], ([a,b,c],[oldA,oldB,oldC]) = >{})Copy the code
-
WatchEffect implementation
The watchEffect parameter is a function that executes the function passed in by watchEffect immediately when the code executes, then responds to trace its dependencies, and rerunts the function when some of those dependencies change. We implemented the above search code using watchEffect
export default defineComponent({ setup() { const state = reactive({ searchValue: "" }); // Load data function loadData(searchValue){}// Use watchEffect to listen for changes to the searchValue const unwatch = watchEffect(() = > { // When the code executes to watchEffect, this function is called immediately and the presence is collected // the dependency of 'state.searchValue' then occurs when 'state.searchValue' // watchEffect is called when changes occur loadData(state.searchValue) }); return{ state }; }})Copy the code
React
The usage
React is similar to Watch with Effect Hook, which allows you to perform side effects in function components
import React, { useEffect, useState } from 'react'
export default function() {
// useState passes in the state data to initialize and returns an array
// The first item of the array is the declared data, and the second argument is a method to call
// Modify the data
const [searchValue, setSearchValue] = useState(' ')
function handleChange(e: React.ChangeEvent<HTMLInputElement>) {
// Modify data in React by calling the method returned by useState
setSearchValue(e.target.value);
}
UseEffect takes two arguments, the first a callback function and the second an array of properties to listen for changes
useEffect(() = > {
UseEffect enters this callback function when the code first calls it, and then
// When the serchValue changes, it enters here again
console.log(111)
},[searchValue])
return (
<div>
<input value={searchValue} onChange={handleChange}></input>
</div>
);
}
Copy the code
In this code, we use useEffect to listen for changes in the searchValue, and then trigger new logic. However, we do not find a way to cancel effect.
UseEffect the second argument is an array, which is used to listen on the data by passing the array a variable to listen on, but there is no way to cancel the listener, so we need a curve to save the country, as shown in the code below
const [isWatch] = useState(true)
useEffect(() = > {
// Use isWatch to determine whether to listen for logic changes
if(isWatch) {
// Listen for data changes
console.log(searchValue)
}
},[isWatch, searchValue])
Copy the code
Calculate the properties inReact
I also found the trail
The computed properties in Vue are familiar to most of you. We use computed properties to simplify complex logical calculations in template. For example, many English websites type firstName and lastName as user names. FirstName and lastName are then displayed together on the screen, and you can use computed properties to manipulate the display
Vue2.0
In the writing
<template>
<div>
<div>
<label>firstName</label>
<input v-model="firstName" />
<label>lastName</label>
<input v-model="lastName" />
</div>
<div>User name :{{name}}</div>
</div>
</template>
<script>
export default {
data() {
return {
firstName: ' '.lastName: ' '}},computed: {
name() {
return this.firstName + ', ' + this.lastName
}
}
}
</script>
Copy the code
Vue3.0
In the writing
The Composition API in Vue3.0 also provides computed APIS for generating computed properties, which are used in much the same way as Vue2.0
import { computed, defineComponent, reactive } from "vue";
export default defineComponent({
setup() {
const state = reactive({
firstName: "".lastName: ""
});
const name = computed(() = > state.firstName + "·" + state.lastName);
return{ state, name }; }});Copy the code
React
In the writing
Before we talk about emulating properties in React, we need to understand some of the React Hook rules.
- It can only be used at the top level
Hook
- Only in the
React
Call from a functionHook
When we use useState in the React function, what does React do if we change the state with setState? React re-executes the functional component, but does not re-initialize useState,useEffect, etc. Instead, it uses the recorded state. How does React know which state corresponds to which useState? React depends on the sequence of Hook calls. So we can’t use hooks in non-topologies like if.
At the same time? Since a change in state causes the entire function to be reexecuted, let’s say we write this logic in our code
const [firstName, setFirstName] = useState(' ')
const [lastName, setLastName ] = useState(' ')
const [other,setOther] = useState(' ')
// With useMemo you can mimic the calculated properties in Vue
const name = firstName + "·" + lastName;
Copy the code
If firstName or lastName changes, the name will be recalculated. This logic is correct. But in fact, if other changes, name will also be recalculated, which we do not want to see. If the calculation logic for name is complex, it can incur unnecessary performance overhead. React provides useMemo to avoid changes in calculation logic caused by non-related attribute changes. UseMemo can be used to simulate the calculation of attributes, as shown in the following code
import React, { useMemo, useState } from 'react'
export default function() {
const [firstName, setFirstName] = useState(' ')
const [lastName, setLastName ] = useState(' ')
// With useMemo you can mimic calculated attributes in Vue when either firstName or 'lastName' changes
// Both trigger a recalculation of 'name', but not for other attribute changes
const name = useMemo(() = > firstName + ', ' + lastName,[firstName,lastName])
const handleChange = (method: Function, e: React.ChangeEvent<HTMLInputElement> ) = > {
method(e.target.value)
}
return (
<div>
<div>
<label>firstName</label>
<input
value={firstName}
onChange={(e)= > handleChange(setFirstName, e)}
/>
<label>lastName</label>
<input
value={lastName}
onChange={(e)= > handleChange(setLastName, e)}
/>
</div>
<div>User name: {name}</div>
</div>
);
}
Copy the code
However, Vue can calculate attributes both get and set, which we can not use useMemo to simulate, of course, if you know how to simulate, please let me know in the comments section, thanks.
conclusion
Front-end technology is developing with each passing day, I said that has learned not to move, but do not learn how to make money to eat, so still want to learn. Vue and React, two of the three main frameworks of the front-end, are often used in daily work. By learning this comparison, they can be combined together to facilitate memorization. This article was first published in the public number ** [front-end some play], learn front-end, interview for a job, on the [front-end some play] **