Finally, the official version of Vue3 has been released, more than two years in development and the efforts of multiple contributors. With the wisdom and efforts of so many excellent developers, Vue3 is destined to become the next mainstream front-end development framework. This article will guide you step by step to learn and understand the use of VUE3, of course, more of my learning process.
That’s what the front end is all about, learning all the time, new technologies coming out every month. If you learn everything, it’s not realistic, so you have to be selective. For example, THERE are three mainstream frameworks, Vue/React/ Angular. I should be involved in and understand the extension frameworks based on these three frameworks.
Some friends at this time will say, our company has not started to use, can not learn. Indeed, our company has not used it, but no matter what technology will have a process, there is a stage in this process can fully enjoy the technology dividend. You learn now, no matter when the technology bonus comes, you can calmly seize the technology bonus period, to obtain the maximum benefit.
Of course, this article is more about how to use it, why the code works the way it does, and how it works. I’ll write an intermediate tutorial on how to use it later.
As the saying goes, it’s better to read a book by hand. I hope you can still do it yourself. Deepen the impression.
Front knowledge
Although I’ve covered a few bits and pieces and API usage, there are a few things you need to know to learn and understand.
- TypeScript – You know and can use it in simple ways
- Vue2.0 Basics – You must have at least some experience with Vue2.0
- You need to be able to use NPM or YARN to install dependencies
Of course, you can’t do all of the above. You can check out the vue2.0 basic notes – advanced notes – in nuggets or in my article, and learn about TypeScript on the TypeScript website.
Some new features of Vue3.0
- Vue3 is backward compatible. Vue3 supports most of the features of Vue2. Using the syntax of Vue2 to develop Vue3, there is no problem.
- Improved performance: 41% reduction in package size, 55% faster first render, 133% faster update, 54% reduction in memory usage.
- The problem with Vue2’s new Composition API is that the code for complex components becomes cumbersome or even unmaintainable. Composition API solves this problem immediately with the launch of a collection of apis.
- Other new features: Teleport(Teleport components), Suspense(resolving asynchronous component loading issues) and global API changes and optimizations.
- Better TypeScript support
Official Vue3 conference video of station B
Vue3 development environment was set up using VUE-CLI
Vue-cli: a standard tool developed by vue.js, the new vue-CLI also provides a graphical interface, which can be used if you are new to the command line.Copy the code
Specific installation steps I this will not describe in detail. The official website is complete and easy to understand. Post the official website address here
Introduction to the basic project directory
| - node_modules -- all project depend on the package in this directory | - public public folder - - | the favicon. Ico - website display icon - | index. The HTML HTML file | - SRC -- - entry Source file directory, the code is basic 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 compatibility. | - eslintrc. Js - Eslint configuration file, Not used as much introduction | - gitignore - used to configure the file does not belong to the git 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
Main.ts entry file
import { createApp } from "vue"; // Import the vue file and export 'createApp'
import App from "./App.vue"; // Introduce a custom component, where everything you see on the page is basically contained
createApp(App).mount("#app"); // Mount the App to the # App node and find the node in the index.html directory of the public directory
Copy the code
Introduction to Composition API usage
Use of setup() and ref()
With the new setup() syntax, you don’t need to write data like you did with vue2.
<template>
<div>
<h2>Vue3 new syntax</h2>
<div>{{girl}}</div>
</div>
</template>
<script lang="ts">
import { defineComponent, ref } from "vue";
export default defineComponent({
name: "App".setup() {
const girl = ref('Tomato Girl');
return{ girl }; }});</script>
Copy the code
Variables declared in vue2 need to be declared in data. Vue3 declares variables through ref and returns them in the setup function to be used on the page.
Changing variables in data in VUe2 requires defining methods in methods. The variable is then modified via an event trigger. So how does vue3 define methods and change variables declared by ref?
<template>
<div>
<h2>Vue3 new syntax</h2>
<div>{{girl}}</div>
<button @click="changeGirls">Change my girl</button>
</div>
</template>
<script lang="ts">
import { defineComponent, ref } from "vue";
export default defineComponent({
name: "App".setup() {
const girl = ref('Tomato Girl');
const changeGirls = () = > {
girl.value = 'Tomato Boy'
}
return{ girl, changeGirls }; }});</script>
Copy the code
Yes, you read that right. Variables declared by ref need to be assigned and read by variable. Value. And event methods no longer need to be declared in methods. Instead, write it directly in the setup function. Isn’t it very simple? And it saves a lot of code. However, variable changes declared by ref need to be modified by variable.value. It’s very inconsistent with how we used to write code. The reactive method described below fits well with our previous usage.
reactive()
It is also a function that takes an Object as an argument.
Both variables and methods can be used as an attribute in Object, and there is no need to add the pesky value attribute when changing changeGirls values. When you return, you don’t need to return one by one. You just need to return a data.
<template>
<div>
<h2>Vue3 new syntax</h2>
<div>{{ data.girl }}</div>
<button @click="data.changeGirls">Change my girl</button>
</div>
</template>
<script lang="ts">
import { defineComponent, reactive } from "vue";
export default defineComponent({
name: "App".setup() {
const data = reactive({
girl: Tomato Girl.changeGirls: () = > {
data.girl = Tomato Boy; }});return{ data, }; }});</script>
Copy the code
So this looks a little bit more concise than ref. Now in template, each output variable is preceded by a data. It’s still a little inconvenient. So how do you write attributes directly like VUe2? You might think of ways to use extended operators. But when you deconstruct it this way it becomes a normal variable and it’s no longer responsive. The solution is to use a new function from vue3, toRefs()
toRefs()
<template>
<div>
<h2>Vue3 new syntax</h2>
<div>{{ girl }}</div>
<button @click="changeGirls">Change my girl</button>
</div>
</template>
<script lang="ts">
import { defineComponent, reactive, toRefs } from "vue";
export default defineComponent({
name: "App".setup() {
const data = reactive({
girl: Tomato Girl.changeGirls: () = > {
data.girl = Tomato Boy; }});return{... toRefs(data), }; }});</script>
Copy the code
As for how to choose to use ref() and recative(), it seems that there are only differences in writing method at present, and specific performance and other aspects need to be checked in the future. But I prefer to use reactive syntax myself.
Add type annotations to data
Since we use typescript syntax. When writing code and methods, we need to standardize and follow TS syntax
<template>
<div>
<h2>Vue3 new syntax</h2>
<div>{{ girl }}</div>
<button @click="changeGirls">Change my girl</button>
</div>
</template>
<script lang="ts">
import { defineComponent, reactive, toRefs } from "vue";
interface DataProps {
girl: string;
changeGirls: () = > void;
}
export default defineComponent({
name: "App".setup() {
const data: DataProps = reactive({
girl: Tomato Girl.changeGirls: () = > {
data.girl = Tomato Boy; }});return{... toRefs(data), }; }});</script>
Copy the code
Vue3. X lifecycle and hook functions
Setup () : Execute before beforeCreate and Created before starting component creation. Create data and method onBeforeMount() : functions executed before the component is mounted to the node. OnMounted () : a function executed after components are mounted. OnBeforeUpdate (): Function executed before component updates. OnUpdated (): Function to execute after the component is updated. OnBeforeUnmount (): Function executed before component unmounts. OnUnmounted (): the function that executes after the component is unmounted. OnActivated (): the component contained in <keep-alive> has two more lifecycle hook functions. Executed when activated. OnDeactivated (): Switches from component A to component B, for example, when component A disappears. OnErrorCaptured (): Activates the hook function when an exception from a descendant component is captured (rarely used. Still learning)Copy the code
Note: Using keep-alive keeps data in memory. For example, if we don’t want to reload data every time we see a page, we can use keep-alive.
Vue2--------------vue3
beforeCreate -> setup()
created -> setup()
beforeMount -> onBeforeMount
mounted -> onMounted
beforeUpdate -> onBeforeUpdate
updated -> onUpdated
beforeDestroy -> onBeforeUnmount
destroyed -> onUnmounted
activated -> onActivated
deactivated -> onDeactivated
errorCaptured -> onErrorCaptured
Copy the code
Through this comparison, it is easy to see that the hook function of VUe3 basically adds an ON on the basis of vue2, but there are also two changes.
- BeforeDestroy becomes onBeforeUnmount
- Destroyed is onUnmounted
Vue3 also has onRenderTracked and onRenderTriggered functions that are officially used for debugging, but I’m not sure how they work.
- OnRenderTracked state tracking
OnRenderTracked literally is state tracking, so it tracks the state of all the responsive variables and methods on the page, the values that we return, it tracks. Whenever there is an update on the page, it tracks it and generates an event object that we use to find problems with the program.
- OnRenderTriggered state triggered
OnRenderTriggered is a state trigger that does not track every value. It gives you information about changing values, and both old and new values are explicitly displayed.
<template>
<div>
<h2>Vue3 new syntax</h2>
<div>{{ girl }}</div>
<button @click="changeGirls">Change my girl</button>
</div>
</template>
<script lang="ts">
import {
defineComponent,
reactive,
toRefs,
onRenderTracked,
onRenderTriggered,
} from "vue";
interface DataProps {
girl: string;
changeGirls: () = > void;
}
export default defineComponent({
name: "App".setup() {
const data: DataProps = reactive({
girl: Tomato Girl.changeGirls: () = > {
data.girl = Tomato Boy; }}); onRenderTracked((e) = > {
console.log(e);
console.log("Status tracking");
});
onRenderTriggered((e) = > {
console.log(e);
console.log("Status tracking");
});
return{... toRefs(data), }; }});</script>
Copy the code
OnRenderTriggered will be used more often in the future. OnRenderTracked is probably used when you don’t know where something went wrong and you need to track all the properties. These two functions are similar to watch. Let’s learn the use of Watch in VUe3
Use and precautions of Watch in VUe3
<template>
<div>
<h2>Vue3 new syntax</h2>
<div>{{ girl }}</div>
<div>{{ boy }}</div>
<button @click="changeGirls">Change my girl</button>
</div>
</template>
<script lang="ts">
import { defineComponent, reactive, toRefs, watch, ref } from "vue";
interface DataProps {
girl: string;
changeGirls: () = > void;
}
export default defineComponent({
name: "App".setup() {
const boy = ref("I am a boy");
const data: DataProps = reactive({
girl: Tomato Girl.changeGirls: () = > {
data.girl = Tomato Boy; boy.value = data.girl; }}); watch(boy,(newvalue, oldvalue) = > {
console.log(newvalue);
console.log(oldvalue);
});
return{... toRefs(data), boy, }; }});</script>
Copy the code
Through the above small example, do you feel vuE3 watch is easy to use? So how do you listen for changes in multiple values? When you listen for multiple values, instead of writing multiple watch functions, you pass in an array. For example, if we want to listen for methods in data as well, which is changeGirls, we can use arrays.
<template>
<div>
<h2>Vue3 new syntax</h2>
<div>{{ girl }}</div>
<div>{{ boy }}</div>
<button @click="changeGirls">Change my girl</button>
</div>
</template>
<script lang="ts">
import { defineComponent, reactive, toRefs, watch, ref } from "vue";
interface DataProps {
girl: string;
changeGirls: () = > void;
}
export default defineComponent({
name: "App".setup() {
const boy = ref("I am a boy");
const data: DataProps = reactive({
girl: Tomato Girl.changeGirls: () = > {
data.girl = Tomato Boy; boy.value = data.girl; }}); watch([boy,() = > data.changeGirls], (newvalue, oldvalue) = > {
console.log(newvalue);
console.log(oldvalue);
});
return{... toRefs(data), boy, }; }});</script>
Copy the code
Vue3 is the listening usage. Although watch can be triggered when the corresponding property or method changes. However, if a variable changes, the corresponding event is handled. I can’t think of a better way to judge. Let me know in the comments section if you know.
Modular use in VUE3
We can find it through the case mentioned above. If more variables and methods are declared in the current component. It still increases the amount of code and readability. At this point we can extract some code and methods with low coupling as modularity. Reference it directly within the component you want to use. For example, a time component
// src/hooks/timeHooks.ts
import { ref } from 'vue'
const nowTime = ref('00:00:00')
const setNowTime = () = > {
nowTime.value = new Date().toString()
}
export {
nowTime,
setNowTime
}
Copy the code
<template>
<div>
<h2>Vue3 new syntax</h2>
<div>{{ nowTime }}</div>
<button @click="setNowTime">Now the time</button>
</div>
</template>
<script lang="ts">
import { defineComponent } from "vue";
import { nowTime, setNowTime } from ".. /hooks//timeHook";
export default defineComponent({
name: "App".setup() {
return{ nowTime, setNowTime, }; }});</script>
Copy the code
Now you can see that this is a lot better than vue2, not having to use mixins anymore.
Teleport components
I call this a standalone component function, and it can mount your component to any DOM you want, so it’s very free-standing. You can’t do this with Vue2.
// Create a modal. vue component under/SRC /components/
<template>
<teleport to="#modal">
<div id="center">
<h2>Just tomato and eggs</h2>
</div>
</teleport>
</template>
<script lang="ts">
export default {};
</script>
<style>
#center {
width: 200px;
height: 200px;
border: 2px solid black;
background: white;
position: fixed;
left: 50%;
top: 50%;
margin-left: -100px;
margin-top: -100px;
}
</style>
Copy the code
Then we open /public/index.html and add a model node.
<div id="app"></div>
<div id="modal"></div>
Copy the code
Preview in your browser at this point and you’ll see that the component is now mounted to the Model node, which is the use of the Teleport component. To be honest, I’m a little confused about how to use this component. Such as hanging on a node alone. What about the underlying responsive development and data transfer? These follow-up estimates to see the source code analysis to understand.
Suspense components
Briefly read, tried to write a usage. But it feels so easy to use. I personally feel that I have not studied his use scenarios and specific usage in detail. I will write a comprehensive version of this component after in-depth research.
<template>
<div>
<Suspense>
<template #default>// Request back shows AsyncComponent has asynchronous requests.<AsyncComponent />
</template>
<template #fallback>// Request and failure display<h1>Loading...</h1>
</template>
</Suspense>
</div>
</template>
Copy the code
The above are my study notes for part of VUE3. The follow-up study is still ongoing. You can refer to one or two
❤️ do me a favor
If you find this article inspiring, I’d like to ask you to do me a small favor:
-
Like, so that more people can see this content (collection does not like, is a rogue -_-)
-
Pay attention to the public account “Tomatology front-end”, I will regularly update and release front-end related information and project case experience for your reference.
-
Adding a friend may not help you a lot, but there are some business issues that can be discussed and exchanged.