Started to prepare
Install Vite
Vite is the unpackaged development server that accompanies the single file component that Vue3.0 was born with for 3.0 compilation
Install the vite command
//yarn Install YARN global add create-viet-app // NPM global install NPM I -g create-viet-appCopy the code
Create a project
Create-vite-app 'XXX project name' short: cva 'XXX project name'Copy the code
New features in Vue3.0
Vue3.0 has been heavily refactored but still retains the friendly lines of Vue. Vue3.0 is perfectly compatible with 2.0, meaning that developers can continue to use it in 3.0 as written in 2.0 and run it perfectly. This is not recommended, however, because some of the syntax written in 3.0 is really easy to use.
Design ideas for Vue3.0
Vue3.0 design pattern differs from 2.0 in that it adopts the idea of multi-module architecture, which reduces the coupling when the Vue framework is referenced in the project and unnecessarily relies on Vue strongly. For example, when Vue3.0 is used in a project, functional modules can be referenced as needed instead of the entire Vue framework. When the project is packaged, only corresponding functional modules will be packaged and the application volume will be greatly reduced. If other platforms need to be adapted and personalized based on Vue3.0 is also greatly reduced, you only need to rewrite the corresponding update module.
Changes in the way applications are created
The way application instances are created in Veu3.0 has also been changed by creating application instances for dynamic functions instead of static ones. The advantages of doing this are:
- When creating program instances, they can be independent of each other and do not interfere with each other.
- The package optimization can be carried out by treeshaking algorithm to reduce the program volume without packing unused modules.
- Embrace the micro front end
The setup () function
It is written as follows:
setup(porps, context) { const formModel = ref({ name: "zhangsan", password: "666", }); Return {formModel,}; },Copy the code
This method can accept two parameters, props and context
The props is passing a reactive value. You can structure the props using toRefs to get the value passed from above, but not structuring it directly causes the properties in the props to become unresponsive.
The context is passing the context and you can find attrs and slots here.
This approach is a particularly important feature of the new Vue3.0 feature that addresses many of the legacy issues of 2.0.
- Setup () has made code much more maintainable, reusable, and readable
- Setup () replaces the mixin() function, eliminating the potential for mixin() to have duplicate names
- Eliminate this and embrace TS
- SetupDate is first looked up for a value obtained from Vue3.0 in Data ().
- Smaller performance costs. Data defined in data 2.0 will be processed in a responsive manner regardless of whether the user needs to use the expression, resulting in higher performance costs. In 3.0, on-demand responsive processing is done through Ref () and Reactive (). Not only does it give the developer choice, but it also dramatically reduces the performance cost.
V – change model
It is well known that in Vue2.0 v-model can only dynamically bind value changes, but in Vue3.0 V-mode can bind multiple different values simultaneously written as v-model: XXX =’ variable name ‘, Emit (‘update: XXX ‘, false) When a child component needs to change the value of the binding, it needs to trigger the change method using the second parameter in the setup function. This is context.emit(‘update: XXX ‘, false)
Example:
<zuiMengDialog v-model:visible="x" :closeOnClickOverlay="false" :save="f1" :cancel="f2" > <template v-slot:content> </div> </template> <template V-slot :title> This is a popup box </template> <template V-slot :footer> <zuiMengButton theme="button" level="main" @click="toggle"> Confirm </zuiMengButton> <zuiMengButton @click="toggle" > Cancel </zuiMengButton> </template> </zuiMengDialog> setup='props,context' > import { SetupContext } from 'vue'; Import {zuiMengButton} from './index' export const close = () => {//visible = context.emit('update:visible', false) } </script>Copy the code
Ref () and reactive ()
Both of these methods are reactive binding functions exposed in Vue3.0. But the difference is this:
Ref (NULL) is generally processed as a reactive object generated by the base data type to obtain a value or change the value to obtain the corresponding value. Moreover, Vue3.0 cancels this.$refs for component binding, and instead uses ref() to bind the component instance for corresponding operation.
Reactive (NULL) typically works with complex data types and generates reactive object values that can be used and modified directly.
setup(props, context) { let count=ref(1) console.log(count.value)//1 count.value=2 console.log(count.value)//2 let state = reactive({ stateSon: 1, stateDaughter: 2 }) console.log(state .stateSon)//1 state.stateSon=2 console.log(state .stateSon)//2 return { count, state } }Copy the code
Template section
In Vue3.0, multiple root nodes can be written in a template, thanks to clever slicing through the Fragment() function. In 2.0 is not implemented, is undoubtedly a major breakthrough.
WatchEffect () function
This function is a listener function that is triggered when the data in props is initialized or changed for the first time, similar to the useEffect() function in React. Note that this method will be called once before the onMounted cycle, but the DOM node is not mounted at this time. If the DOM node is operated, an error will be reported.
This method passes two arguments
The first argument is the callback (effect() side effect function). Effect () also receives an onInvalidate() side effect function, which is used to clean effect() during component destruction. The idea is similar to react, in that when you use a listener, you need to clear the listener during component destruction.
The second parameter is options which is a pointer scheduler that controls whether the watchEffect event is triggered before or after the data change Flush has two values ‘post’ and ‘pre’
Setup (props, context) {watchEffect(() => {// callback function body}, {//options value flush: 'post'})})}Copy the code
The watch () listener
Watch works the same as it did in 2.0, but the writing style has changed
Watch listens for a single notation in the setup function
setup(props, context) { let count=ref(1) let state = reactive({ stateSon: 1}) // Reactive watch(() => stat. stateSon, // Data to be listened to (newVlaue, oldVlaue) => { Parameter 2 is old console.log(newVlaue) // callback function executed after data change}, {lazy: Count (count1, (newVlaue, oldVlaue) => {count (newVlaue, oldVlaue) => { Console. log(newVlaue) // Callback function executed after data change}) return {count, state}}Copy the code
Listen for multiple data writing methods
setup(props, context) { let count=ref(1) let countTwo=ref(2) let state = reactive({ stateSon: 1, stateDaughter: StateSon () => state.stateson, () => state.statedSlaughter) ([sonNewVlaue, aughterNewVlaue], [sonOldVlaue aughterOldVlaue]) = > {/ 1 / parameters for the new value, Parameter 2 is old console.log(' callback triggered ') // callback function executed after data change}, {lazy: First create false} / / listening) / / listening watch ref type ([count, countTwo], ([countNewVlaue countTwoNewVlaue], [countOldVlaue, countTwoOldVlaue]) = > {/ 1 / parameters for the new value, Console. log(' callback triggered ') // Callback executed after data change}) return {count, countTwo, state}}Copy the code
Life cycle change
In Vue3.0, the lifecycle is also called as written in 2.0, which has been optimized to be imported on demand and called in the setup() function
However, it is important to note that the created() and beforeCreated() life cycles cannot be used in the setup() function between their execution before the setup() function
import { onBeforeMount, onMounted, Updated} from '@vue/composition-api' setup () {onBeforeMount(() => {console.log('onBeforeMount life cycle was called ')}) OnMounted (() => {console.log('updated lifecycle ')}) updated(() => {console.log('updated lifecycle ')})}Copy the code
Changes to responsive data implementation
Vue2.0 is data hijacking via Object.defineProperty, adding set and GET methods to each data and updating function-dependent collection when get() of data is triggered. When the set() of data is triggered, the collected update function is cyclically called to update the view to realize data responsiveness. In Vue3.0, Proxy(Proxy) and Reflect(mapping) are implemented to realize data responsiveness, which perfectly solves some drawbacks of Vue2.0 responsiveness: For example, the new properties of objects or arrays cannot be realized in response mode and need to be added manually, the realization of array in response mode requires extra processing, and too much responsive data (because of lazy optimization in Vue3.0 in response mode, no matter how big the data is, as long as the user does not access it, it will not be processed in response mode).
Computed () computes changes in attributes
Computed properties in Vue2.0 are read-only and cannot be changed, but computed values can be changed in 3.0
Setup () {const count = ref(1) const computedDate= computed(() => count.value +1) // Change the value returned by count +1 const is not allowed computedDateTwo= computed({ get:() =>count.value + 666, set: (value) => count.value = value}) // addCount2.value = 123 // Assignment method return {count, computedDate, computedDateTwo}}Copy the code
Some attributes removed from Vue3.0
This.$refs. XXX Vue3.0 removes binding of component instances using this method but the new method is binding by ref(null) as follows
<template> <demo> <div> <zuiMengForm :model="formModel" :rules="rules" ref="ceShiForm"> <zuiMengFormItem Lable ="password" @click="clickCeShi" prop="password"> {{formModel.password}} </zuiMengFormItem> </template> setup(){ const ceShiForm = ref(null); const clickCeShi = () => { ceShiForm.value.validate(); }; }Copy the code
this.$emit
The this.$on attribute methods were removed from Vue. Vue3.0 decided that this was not what Vue should do
Optimization strategies in Vue3.0
Static node lifting
Vue3.0 stores nodes by classification during compilation. If static nodes need to be compiled, the nodes are stored outside the compilation function and can be directly used in subsequent updates without compilation and update, which greatly saves compilation time
Patch marking and dynamic property logging
When template compilation is performed in Vue3.0, dynamically compiled elements are encountered in nodes, which are marked by bit operation according to different element categories. After labeling, diff algorithm performs different processing according to different labeling during rendering, which reduces some unnecessary operations and greatly improves rendering performance.
Caching event handlers
When compiling a callback function, the compiler preferentially searches for it from the cache. If it finds a callback function, it uses it. If it cannot find a callback function, it generates a new callback function and stores it in the cache. Easy to use in the next update, avoiding each re-creation greatly reduces performance loss
Block block
If a parent element has many children, the compiler will find the dynamic children used under the parent element and store them in the array of dynamic children of the block object created by the parent element. The diff algorithm will directly compare the changes of elements in the dynamic subelement array for updating, greatly improving the update efficiency.
conclusion
Vue has made earth-changing changes on the basis of 2.0, which not only optimized the shortcomings of 2.0, but also fully backward compatibility. It is especially friendly to the developers of the previous version of Vue. In addition, the new optimization strategy in Vue3.0 saves resources and improves performance, making Vue3.0 more powerful and worth using for development projects. Although the compatibility of the fly in the ointment has not been optimized for the time being (Vue3.0 has basically abandoned Internet Explorer), it does not prevent Vue3.0 to emerge, looking forward to the future of Vue3.0 shine.