On September 19, 2020, Vue updated the official version of 3.0. It has been several months. As a front-end checker, it is time to start learning. Here is a summary of vue3 in the end what updates, to help you do not have time to understand vue3 friends to a quick start.
What do you think of VuE3?
Vue2. X is a relatively stable version, is also very long period of time we use the version of community ecology has been very perfect, so, if we don’t have to worry yet to upgrade to the vue3, waiting vue3 ecological mature, after all, still need a period of accumulation, but as the front field indispensable a skill, Of course, I want to be able to get to the front end of the technology iteration is so fast.
So let’s take a look at the advantages and features vuE3 has over VUE2. After the community is perfected, we can directly use these technologies in our work. After all, vuE3 has attracted the attention of various industry leaders since it came out. Therefore, whether it is simply to experience using VUe3 as an API developer, or to learn the programming ideas of Utah University, it is necessary for us to learn about it. This article will use the syntax of VUe3 to write, and the following is the official website address of VUe3
Vue3. X official website address
You can also switch to 3.X-beta by clicking on the top left corner of the current version’s website
How to create a VUE3 project
- Use the latest version of vuE-CLI. After the upgrade, you will be allowed to choose the version when creating the project. Just choose vuE3 version, as shown below:
Just select version 3 and use the same option as vue2 to complete the project creation with a green light. This project is not much different from vue2, but also uses WebPack to build the project. However, vue3 provides another way to create the project:
- The second isviteWay to generate a project, do large projects of classmates know, webpack in our local development process, every subtle change, will lead to a very long time to repackage, for many large projects, the consumption of this time is too long, this also is a sore point for a long time, so the vue3 carry vite was born, Vite still works based on Node, the principle is that the browser now supports es6 import, encounter import will send an HTTP request to load the file, Vite intercepts these requests, do some precompilation, save webpack lengthy packaging time, improve the development experience. Make local development more efficient
- At this time, some people may ask, is webPack still used, so this is no doubt, of course, useful, the first Vite ecosystem is not perfect, can not guarantee its stability, the second rely on Vite for local development, before the online packaging work still need webpack support to use, so, Webpack is still needed, of course, new models like Vite are still worth looking forward to, hopefully we can make this technology more mature and make our local development more efficient.
Project directory
|-node_modules - all project depend on the package in the directory | - public - public folder - | the favicon. Ico - website display icon - | index. The HTML - the entrance to the HTML file | - SRC, source files directory, Code written mostly in this directory - | assets - placed static file directory, such as the logo. The pn is here - | components - Vue component files, custom components will be on this -- -- - | App. Vue - the root component, In this Vue2 have - | main. Ts - entry documents, because the TypeScript so end is ts - | shims - vue. Which s - class files (also called definition file), because. The file is not recognized in the ts at the end of the vue, So be definition file | -. Browserslistrc -- -- public target browsers and node between different front-end tool version of the configuration file, role is to set up minimum adapted version compatibility. | - eslintrc. Js - Eslint configuration file, Not used as much introduction | - gitignore - used to configure the file is uploaded to git file management | - package. Json - command configuration and package management file | - README. Md - documentation of the project, Use markdown syntax written | - tsconfig. Json - about TypoScript configuration file | - yarn. The lock - using automatically generated file after the yarn, the yarn management, installing a yarn package of important information stored in the yarn. The lock fileCopy the code
The setup () and ref ()
The editor uses vscode. To get syntax tips for vue3, download the **Vue 3 Snippets ** plug-in from the vscode store.
- Since we are learning VUe3, the following syntax will be written in VUe3
First of all, we will write a simple transformation of the app.vue page, the old rules, all empty, their own operation, the following to write a simple store name system function to analyze the new syntax:
Let’s start by comparing the differences in syntax
- In VUe2, to implement such a program, you needStudents array,Select the personAnd then,methodsTo define a selection methodselectStuFn
- For vue2, it is the same as the beforeCreate and create life cycle functions. For vue2, it is the same as the beforeCreate and create life cycle functions. For vue2, it is the same as the beforeCreate and create life cycle functions. In vue3 his life is not only a periodic function, at the same time, through this function, we need to define the vue2 of data, the methods, watch, computed attribute, so we said to the definition of the above two properties and methods are defined in one of, but finally need to return back, Valuede (see figure 1), and eventually we need to return either a property or a method
- Defined in VUe2 indataThe value inside will automatically become reactive, so we don’t have to do anything to use it inside the template, okay
- In VUe3, as shown above, we need to include the ref keyword to define it as a responsive data.
- The ref function is a function that turns a normal variable into a Proxy reactive variable
- Another use of ref can call the native DOM
So here’s a summary of setup and ref:
- The setup function is a lifecycle hook that corresponds to the beforeCreate and CREATE functions in Vue2 and is the entry to vue3’s Composition API.
- We defined by the function in vue3 vue2 of data, the methods, watch, computed properties
- The setup function must return a value. It must return an object containing all of the attributes (including data,methods, etc.) used in the template template.
- In setup, the ref life reactive data must be evaluated or assigned using the. Value method, but template does not need to use. Value **
- Ref can also call the native DOM
- Setup The first parameter to receive is props, which is a property defined on the component (same as vue2), but the received props must be defined in the props property first, otherwise it will not be received
- The second parameter that setup receives is context. In js, this parameter represents the context. It exposes the component’s property, which is just a normal javaScript object. So I think you all know what to do.
! It is important to note that props is reactive data and you cannot use ES6 to deconstruct it because it eliminates the responsiveness of prop. To structure the props, we need toRefs in the setup function to do this safely, which we’ll talk about later.
It is not hard to see, the above method for vue2, many people may feel more troublesome, and even some wonder why you need to use the * *. The value of the way, but in the template and don’t need, written as seems to be some against humanity, and the second if we define many also need to return a lot of value to go out, will feel very troublesome, So, let’s take a look at vue3’s next new API** to see how to solve this problem.
usereactiveFunction optimizer
As you can see above, it is not very convenient to write it, so we can optimize it by using this function instead of using **. Value **.
In the figure above, I’ve pointed out the differences with arrows, so I can summarize the following points for you
- Instead of using ref to declare response for attributes, I just need to define a data object, put all the attributes I want in data, and finally return data.
- ** instead of using **. Value, use data.**, which is more convenient to understand. Of course, template also needs to be added, personally, I think this way of writing is clearer and easier to understand.
- Instead of returning a bunch of things, you just return an object, which is a little bit more concise.
! Template does not need to use **. Value, but now we need to add data. Isn’t that more trouble? Can we just use attributes instead of adding anything else to template**? B: Sure.
- If you want to do that, some of you might think, well, as long as I don’t return objects, why don’t I just return all properties? You’re right, just return so the property will do, and you can implement it, but how do you implement it?
- Some of you might think, well, why don’t you just assign to the structure? Just
rerurn {... data}
Isn’t that all right? I can tell you straight away that it doesn’t work, so why, here and up herepropsSame principle, because we’re defining responsive data, and if we just do this structure assignment we’re going to break the responsive properties, so that the data is no longer responsive, so there’s no change when you click the button, so we can’t do that. - So how do we do that? ToRefs ()** toRefs()** toRefs()
- Some of you might think, well, why don’t you just assign to the structure? Just
The toRefs() function returns the deconstruction of reavtive()
Let’s just tweak it a little bit and you can see how this works.
- This way you can use it directly in the template
- It’s easy to imagine that this method is designed to get through its method structure without breaking its responsiveness, that’s all.
The lifecycle of VUE3
-
What is the life cycle
- Vue is componentized development, the life cycle of a component from birth to death.
- The latter part of life is the same as the period from birth to death. Different things can be done in different periods.
-
Comparison of vuE2 and VUE3 life cycles
-
vue2 vue3 Comparison of partial differences between VUe2 and 3 beforeCreate setup Setup () : Execute before beforeCreate and Created before starting component creation. Create data and Method created setup beforeMount onBeforeMount The function executed before the component is mounted to the node. mounted onMounted A function that executes after the component is mounted. beforeUpdate onBeforeUpdate The function executed before the component is updated. updated onUpdated A function that executes after the component has been updated. beforeDestroy onBeforeUnmount Unload previously executed functions. Compared to changing the name destroyed onUnmounted A function executed after unloading. activated onActivated The included component has two additional lifecycle hook functions. Executed when activated. deactivated onDeactivated For example, switching from component A to component B is performed when component A disappears. errorCaptured onErrorCaptured The hook function is activated when an exception from a descendant component is caught. onRenderTracked Vue3 added cycles for development and debugging onRenderTriggered Vue3 added cycles for development and debugging -
Let’s start with a quick comparison, and we see these differences
-
Vue2’s beforeCreate and CREATE become setup
-
Vue2’s destroyed and beforDestroy are changed to onUnmounted: Unmounted is more semantic
-
Except for setup, the name of vue2 is mostly the same, with an on in front of it
-
About debugging function, the official document also does not have too much explanation, most of the bloggers for the two functions are very fuzzy, here I use after tests found that these two functions are all about component state after the change can be traced to each response type data before and after the status is of the order, and the event has a parameter, So I think this is the state tracking function, the purpose is to prepare to see the change process of each responsive data in our local development. Of course, the official documents behind this will certainly be clear.
-
-
Vue3 watch changes and watchEffect()
The basic use of the Watch listener is to listen for changes in the old and new values of a value. In VUe2, it takes the form of an object and then listens for different values in vue3
import {watch} from 'vue'
watch(a, (newVal, oldVal) = > {
console.log(newVal, '= = =', oldVal)
})
Copy the code
In fact, vue3’s syntax is now the same as that of various UI frameworks. Each API is introduced in the same way that it is introduced on demand
Looking at the syntax, here the Wacth function takes two arguments, the first argument is the value we are checking for, and the second is the callback function, which has both the old and new values as before.
Meanwhile, Vue3’s Watch supports listening on multiple values at the same time, in the form of an array, as follows:
import {watch} from 'vue'
watch([a, b], ([newValA, newValB], [oldValA, oldValB]) = > {
console.log(newValA, newValB, '= = =', oldValA, oldValB)
})
Copy the code
Listen on multiple values, the corresponding callback function parameters are also multiple old and new values, such listening will make our business do some comparative judgment more flexible, the above is the basic use of Vue3 watch, of course, there is another place to pay special attention to is.
- Watch can only listen to reactive data defined by the **ref() function, and reactive()** will report an error.
-
What does this error mean? It tells us that watch can only listen for, 1: values that have getter/setter properties. 2: a ref attribute, which is the data declared by **ref(). 3: an object returned by reactive()**. 4: an array, then as shown in the figure above, data.selectPeople will report an error because we are listening for a value that is not one of the above four cases.
- So what do we want to do first? Why can’t we listen in? Vue2 has a watch property called deep Listening. Why? So deep listening is the essence of cyclic references in order to solve the problem, then we know that the depth of the vue2 listening is actually use the recursion to solve, thus causing the performance is not very good, so the official also is not very recommended deep, so the problem is that when you go to listen to an object or array, both before and after the object is a circular reference, NewVal and oldVal always have the same value, which is why this is the case. Therefore, it is easy to solve the above problem by simply returning a new value from a function, which can solve the reference problem as follows
In contrast, Vue3’s Watch is more flexible with new scenarios and more usage methods, both syntactically and for business purposes.
WatchEffect is also a new API from VUe3. The syntax looks like this:
import {watchEffect} from 'vue'
watchEffect(() = > console.log(name))
Copy the code
He is a method that receives a callback function, he doesn’t need to specify who listens, it will automatically collect rely on, as long as the callback function is used in the property, at the time of change, will be to trigger the callback function, it will become very simple, in the business, we don’t need to be especially listening in so-and-so attributes, but write him directly in the callback function, It automatically collects dependencies for us.
Vue3 modularity
In the use of VUe2 project, if we reuse some functions, we will use mixin to mix, while in VUe3, the new module reuse mechanism will be more convenient, let’s first write a simple real-time online time display function, as follows:
Is to click the button to trigger a time display function is very simple, the page effect is like this, I believe students, can easily understand:
Now we want to reuse this logic. In VUe2, we will reuse a large part of our code logic if we use mixin-style development. Let’s look at what we need to do if vuE3 wants to reuse this functionality:
- The first step is to extract the logic in **setup()** into a TS file, and then export the methods and properties we need. Here I directly export a ref() wrapped object. If you want to be more detailed, you can also export data and use the ref() wrapped response in the component. It’s very simple to use, as shown below:
- As you can see, it only takes two parts. Just import and return in **setup()** to complete the reuse of a function
It can be said that VUe3 has a very big improvement in module reuse compared to VUe2. This change will make the module between components become extremely flexible. Are you looking forward to this writing method?
Teleport, vuE3’s teleportation component
Teleport means Teleport, so the domestic translation is Teleport component, how to understand this Teleport component.
- One thing we all know, whether it’svueOr is itreactIn the HTML of the entry file, there is only one container
<div id='app'></div>
We call it the portal, and all of the components on the page are actually mounted on this node, and when we open up the page, we can see that there’s only one node in the outermost layer that controls the app. - Wrote a popup window components or message friends all know that, as the global only a state of the components, we don’t want him with our component, we hope that he is independent of the app component, therefore, in the most excellent UI framework, this kind of advanced component, generally to adopt the way of the newly created a node, pulled out of the app node, This is easier to control and can be deleted even after use. thenTeleoirtA component is actually something that can be independent of the new node outside of the app, and we all know the entry file
index.html
Both have a node called APP, we add a new app2, as shown in the figure.
To use this node, let’s create a simple popover component. This component is also very simple to display in the center of the page. Let’s see how this component differs from vue2:
- We can see that this component outside wrapped with a layer of Teleport tags, and have a the to attribute, so first of all, to use the Teleport components requires that the label packages, so the to attribute means I will mount on which node, as shown above, we created a app2 node, we want to mount on the node, To =’app2′, we create a transient component, using the same method as vue2. Let’s see what happens:
Ok, that is so simple, to complete the creation of a transient component, such a component for some states of a single component creation, become more silky, will not cause any damage to the internal components used, there will be no style pollution and other problems, very practical.
Vue3’s asynchronous request component Suspense
In vue3, asynchronous components are an indispensable part of daily development, such as interface requests, picture requests and requests caused by various asynchronous operations. In VUE2, we need to judge these states manually. But vue3 provides this very considerate component, which translates to suspense in Chinese. It provides two templates, namely two slots, one is what will be displayed when the request is not returned, and the other is what will be displayed when the request is successful. Let’s write one, let’s write an asynchronous component first. This interface right here is an interface that returns a random image.
Here is a random return image, let’s introduce this component to use:
- Components wrapped up in Suspense tags are asynchronous components. In Suspense, there are two slots for success and failure, which will display the content accordingly. This makes it easier to make redundant decisions and is also useful
! Of course, official note, this is an implementation of the API, may change later, of course, we also need to know in advance of such a way of writing.
An explanation of some small points of VU3
-
What is the Composition API?
- The Compositon API is not one API, it’s a set of apis that we call collectively. In VUe2, we define attributes and methods in methods, computed, watch, data, etc., to work with page logic, We call this approach the Options API. In this way, when the project is too large, we find that when a method defines dozens of methods, it becomes very troublesome to be prepared to know the function of this and what each method does. Composition API is the solution to this problem
- In Vue3 Composition API, our code is organized according to logical functions. All apis defined by a function are grouped together (more cohesive, less coupled). By doing this, we can quickly locate all apis used by this function, even if the project is large and has many functions.
-
Is **ref() or reactive()** better?
- I prefer reactive()**. There is no difference between the two methods except the writing method.
-
What’s the difference between vue3’s createApp() entry?
- Vue2 uses new Vue() and vue3 uses createApp(), which is essentially the same way. However, before we registered some global components, mixin, plugins, prototype, etc., we used this way.
Vue.mixin(... xxx)
In vue3, **createApp()** returns a new app, which avoids this problem. - At the same time, such writing method adopts the way of chain call when calling, similar to koA, Express and other frameworks, as shown in the following figure:
- Vue2 uses new Vue() and vue3 uses createApp(), which is essentially the same way. However, before we registered some global components, mixin, plugins, prototype, etc., we used this way.
-
How do I register global components for Vue3?
-
app.component('componentName', component) Copy the code
-
-
How do I register custom instructions with Vue3
-
/** v-snine */ app.directive('snine', { inserted: function (el) { el.snine() }, }) Copy the code
-
-
How does Vue3 blend globally
-
const app = createApp(App) app.mixin({ beforeCreate() { console.log('I'm a global mixin')}})Copy the code
-
-
How does Vue3 mount properties and methods globally
-
const app = createApp(App) // To mount $axios on global CTX (this), you need to mount it on globalProperties app.config.globalProperties.$axios = axios Copy the code
-
-
Is there a filter for Vue3?
- Vue3 filter has been removed and is no longer available
-
Can the life cycles of Vue2 and Vue3 be intermixed? How does it work?
- The life cycle of vue2 and VUe3 can be used together, the API is the same as before, but I think if you use VUe3 to write the project, I don’t think it is necessary to use VUe2 API. Of course, if you must use vue3, I can tell you that the PRIORITY of VUe3 API is better. Print each life cycle and you will find that vue2 is executed before vue3 is executed first.
-
Can vue2 be written in Vue3?
- Vue3 is progressive and backward compatible, which means we can still use the syntax of VUE2 to complete the project, which is what WE are very thoughtful about for you to consider the project upgrade.
.
conclusion
Front-end learning is a long way to go. If you want to program for salary, you should always try to learn new technology, new knowledge, and learn other people’s writing and thinking. The road is long and the road is long