In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article introduces the relevant knowledge of "what is the difference between creating applications in React and Vue". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
React vs Vue: the Legend continues
A few years ago, I decided to try to build a fairly standard To Do App in React and Vue. Both applications are built using the default CLI (React's create-react-app and Vue's vue-cli). My goal is to write unbiased content and to provide an overview of how to use these two technologies to perform certain tasks.
When React Hooks was released, I added "2019 Edition" to the end of the original article, which replaced the use of Class Components with Functional Hooks. With the release of Vue version 3 and its component API, it's time to update this article again with version 2020.
Let's take a quick look at the appearance of these two applications:
The CSS code for the two applications is exactly the same, but their locations are different. With this in mind, let's look at the file structure of the two applications:
In the end, both of them can achieve the same goal, and there is nothing to say that you can no longer construct files differently in React or Vue. It really depends on personal preference. You will hear a lot of discussion from the developer community about the structure of CSS, especially about the structure of React, because there are many CSS-in-JS solutions, such as style components and emotions. By the way, this is the literal meaning of CSS-in-JS. Although these features are useful, so far we will only follow the structures listed in the two CLI.
But before going any further, let's take a quick look at the look and feel of typical Vue and React components:
A typical React file:
A typical Vue file:
Now that it has been solved, let's delve into the details.
How do we mutate the data?
But first, what does "mutation data" even mean? Does that sound a little technical? Basically, this just means changing the data we have stored. So if we want to change the value of a person's name from John to Mark, we will "mutate the data." So this is the key difference between React and Vue. Although Vue essentially creates a data object in which you can update data freely, React handles it through state hooks.
Let's take a look at the settings in the following two pictures, and then we'll explain what happened:
React status:
Vue status:
Therefore, you can see that we have passed the same data to both, but the structure is somewhat different.
With React or at least from 2019, we usually deal with state through a series of Hooks. If you haven't seen these concepts before, they may seem a little strange at first. Basically, it works as follows:
Suppose we want to create a to-do list. We may need to create a variable called list, which may require an array of strings or objects (for example, if we want to give each to-do string an ID and other things, we can write const [list,setList] = useState ([]). Here we use a hook called Hook by React-called useState. This basically allows us to retain local state in the component.
In addition, you may have noticed that we passed in an empty array [] inside useState (). What we put in it is what we want the list to set up initially, and in our case, we want an empty array. However, as you can see from the figure above, we pass in some data inside the array, which is ultimately the initialization data for list. Want to know what setList does? I'll explain more about this later!
In Vue, you typically place all the variable data for a component in the setup () function, which returns an object containing the data and functions to be exposed (which basically means that what you want to be able to use) is used in your application. You'll notice that each state data in the application (that is, the data we want to be able to mutate) is wrapped inside the ref () function. This ref () function, which we imported from Vue, allows our application to update any time the data is changed or updated. In short, if you want to create mutable data in Vue, assign a variable to the ref () function and put any default data in it.
So how do we reference mutable data in our application?
Well, suppose we have some data named name that is assigned the value of Sunil.
In React, because we used useState () to create a smaller state, we probably already created something in the way const [name,setName] = useState ('Sunil'). In our application, we will refer to the same data by simply calling name. Now, the main difference here is that we can't simply write name = 'John', because React has appropriate restrictions to prevent this simple, random mutation. So, in React, we will write setName ('John'). This is where the setName bit works. Basically, in const [name,setName] = useState ('Sunil'), it will create two variables, one of which will become const name =' Sunil', and the second const setName will be assigned a function that can recreate the name with the new name. Value.
In Vue, it is inside the setup () function and is called const name = ref ('Sunil'). In our application, we will refer to it by calling name.value. With Vue, if we want to use the value created inside the ref () function, we will look for .value on the variable instead of simply calling it. In other words, if we want the value of a variable that holds the state, we will look for name.value instead of name. If you want to update the value of name, you can do so by updating name.value. For example, suppose I want to change my name from Sunil to John. I can do this by writing name.value = "John". I'm not sure what it feels like to be called John, but hey, it happened!
In fact, React and Vue do the same thing here, creating data that can be updated. Whenever a piece of data wrapped inside the ref () function is updated, Vue essentially combines its own name and setName versions by default. React requires that you call setName () with an internal value to update the status, and if you try to update the value inside the data object, Vue assumes that you want to do so. So why does React separate values from functions? Why use useState ()? In essence, React wants to be able to rerun some lifecycle hooks whenever the state changes. In our example, if you call setName (), React will know that some states have changed, so you can run these lifecycle hooks. If you change the state directly, React will have to do more to track changes and lifecycle hooks to run, and so on.
Now that we have some workarounds, let's learn more details by looking at how to add a new project to the two to-do lists.
How do we create new to-do items? React:const createNewToDoItem = () = > {const newId = generateId (); const newToDo = {id: newId, text: toDo}; setList ([... list, newToDo]); setToDo (");}; how is React done?
In React, our input field has a property named value. This value is automatically updated each time its value is changed through an onChange event listener. JSX (basically a variant of HTML) is as follows:
Therefore, it updates the status each time the value is changed. The handleInput function is as follows:
Const handleInput = (e) = > {setToDo (e.target.value);}
The createNewToDoItem function is now triggered every time the user presses the + button on the page to add a new item. Let's take a look at this feature again to see what happened:
Const createNewToDoItem = () = > {const newId = generateId (); const newToDo = {id: newId, text: toDo}; setList ([... list, newToDo]); setToDo ("");}
Essentially, the newId function is basically creating a new ID that will provide us with a new toDo item. The newToDo variable is an object with an ID key that has the value of newId. It also has a text key that uses the value in toDo as its value. This is the same as the toDo to be updated when the input value changes.
Then we finish using the setList function and pass in an array containing the entire list and the newly created newToDo.
If... If the list bit looks strange, the first three dots are called scatter operators, which basically pass all the values in the list as separate items, rather than simply passing the entire item as an array. Confused? If so, I strongly recommend that you read the distribution carefully, because it's great!
Anyway, finally we run setToDo () and pass in an empty string. So our input value is empty, so we can enter a new toDos.
Vue:function createNewToDoItem () {const newId = generateId (); list.value.push ({id: newId, text: todo.value}); todo.value = "";} how is Vue done?
In Vue, there is a handle called v-model on the input field. This enables us to perform operations called two-way binding. Let's take a quick look at the input fields and explain what happened:
V-Model binds the input of this field to the variable we created at the top of the setup () function and exposes it as a key to the object we return. So far, we haven't covered what the object returned, so for your information, this is what we returned from the setup () function inside ToDo.vue:
Return {list, todo, showError, generateId, createNewToDoItem, onDeleteItem, displayError}
Here, list,todo and showError are our state values, while all other functions are functions that we want to be able to call elsewhere in the application. OK, back from the tangent, when the page loads, we must set todo to an empty string, for example: const todo = ref (""). If you already have some data, such as const todo = ref ("add some text here"): our input field will be loaded if some text has been added inside the input field. Anyway, going back to it as an empty string, whatever text we type in the input field must be bound to todo.value. This is actually a two-way binding-the input field updates the ref () value, while the ref () value updates the input field.
So, looking back at the previous createNewToDoItem () code block, we see that the contents of todo.value are pushed into the list array-by pushing todo.value into list.value- and then updating todo.value to an empty string.
We also use the same newId () function as in the React example.
How do we remove it from the list? React:const deleteItem = (id) = > {setList (list.filter ((item) = > item.id! = = id));}; how does React do it?
So, although the deleteItem () function is in ToDo.js, I can easily reference it by first passing the deleteItem () function to ToDoItem.js as a prop:
First, the function is passed down so that children can use it. Then, inside the ToDoItem component, do the following:
DeleteItem (item.id)} >-
All I have to do is reference the function inside the parent component, which is props.deleteItem. By now, you may have noticed that in the code example, we just wrote deleteItem instead of props.deleteItem. This is because we use a technique called deconstruction, which allows us to take a portion of the props object and assign it to variables. Therefore, in our ToDoItem.js file, we have the following:
Const ToDoItem = (props) = > {const {item, deleteItem} = props;}
This creates two variables for us, one is called item, which is assigned the same value as props.item, and the other is deleteItem, which assigns a value from props.deleteItem. We could have avoided the whole destructive thing by using only props.item and props.deleteItem, but I think it's worth mentioning!
Vue:function onDeleteItem (id) {list.value = list.value.filter (item = > item.id! = = id);} how is Vue done?
A slightly different approach is needed in Vue. Basically, we have to do three things here:
First, we will call the function on the element:
-
Then, we must create an emit function as a method in the subcomponent (in this case, ToDoItem.vue), as shown below:
Function deleteItem (id) {emit ("delete", id);}
At the same time, you will notice that when we added ToDoItem.vue to ToDo.vue, we actually referenced a function:
This is called a custom event listener. It listens for situations where the launch is triggered using the string "delete" in any case. If you hear this message, it will trigger a function named onDeleteItem. This function is located inside ToDo.vue, not in ToDoItem.vue. As mentioned earlier, this function only filters ID from the list.value array.
It is also worth noting here that in the Vue example, I can simply write the $emit part in the @ click listener, as follows:
-
This will reduce the number of steps from 3 to 2, depending on personal preference.
In short, child components in React can access the parent function through props (as long as you pass props, which is quite standard practice, in other React examples, you will encounter a lot of work), while in Vue, you can issue events from the child, usually collecting them in the parent component.
How do we pass event listeners? React:
Event listeners for simple events, such as click events, are simple. This is an example of how we create a click event for a button that creates a new ToDo project:
+
It's super simple here, almost like how we're going to use vanilla JS to deal with embedded onClick. As described in the Vue section, it takes longer to set up an event listener for processing each time the Enter key is pressed. This essentially requires that the onKeyPress event be handled by the input tag, such as:
Whenever the function recognizes that the "enter" key has been pressed, it triggers the createNewToDoItem function, such as:
Const handleKeyPress = (e) = > {if (e.key = "Enter") {createNewToDoItem ();}}; Vue:
In Vue, it's very straightforward. We only use the @ symbol, and then use the type of event listener we want to do. So, for example, to add a click event listener, we can write the following code:
+
Note: @ click is actually a shorthand for writing v-on:click. The cool thing about Vue event listeners is that you can also bind a lot of things, such as .once, which prevents event listeners from being triggered multiple times. There are many shortcuts when writing specific event listeners to handle keystrokes. I find that every time I press the Enter key, it takes a long time to create an event listener in React to create a new ToDo entry. In Vue, I can simply write:
How do we pass the data to the subcomponents? Reaction:
In react, we pass the props to the location where the subcomponents were created. Such as:
Here, we see two props passed to the ToDoItem component. From now on, we can now reference them in subcomponents through this.props. Therefore, to access item.todo prop, we just need to call props.item. You may have noticed that there is also a key prop (so technically, we are actually passing three props). This is mainly used inside React because it makes it easy to update and track changes between multiple versions of the same component (we have it here because each todo is a copy of the ToDoItem component). It is also important to ensure that your component has a unique key, otherwise React will warn you in the console.
Vue:
In Vue, we pass the props to the location where the subcomponents were created. Such as:
When this is done, we pass them to the props array of the child component, as follows: props: ["todo"]. These names can then be referenced in the subcomponents by their names, so in our case it is todo. If you are not sure where the prop key is placed, this is the appearance of the entire export default object in the subcomponent:
Export default {name: "ToDoItem", props: ["item"], setup (props, {emit}) {function deleteItem (id) {emit ("delete", id);} return {deleteItem,};},}
One thing you may have noticed is that when traversing data in Vue, we are actually traversing list rather than list.value. Trying to traverse list.value doesn't work here.
How do we send the data back to the parent component? React:
First, the function is passed to the subcomponent by referencing it as a prop where it is called. Then, by referring to props.whateverTheFunctionIsCalled (if deconstruction is used) or whatTheFunctionIsCalled, you can add a call to a function on a child element in any way, such as onClick. This then triggers the function in the parent component. We can see an example of the entire process in the "how do we remove from the list" section.
Vue:
In the child component, we only write a function that returns the value to the parent function. In the parent component, we write a function that listens to when the value is emitted, and then triggers the function call. We can see an example of the entire process in the "how do we remove from the list" section.
That's all for the content of "what's the difference between creating applications in React and Vue". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.