In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article focuses on "how to use the new features of Vue3.0". Friends who are interested may wish to take a look. The method introduced in this paper is simple, fast and practical. Now let the editor take you to learn how to use the new features of Vue3.0.
1. New changes brought about by Vue3
Performance improvement (zero cost: from vue2 to vue3)
Faster rendering for the first time, faster diff algorithm, less memory consumption, smaller package size,....
Better Typescript support (it is more convenient to write TS under vue)
Provide a new way to write code: Composition API
2. The syntax of these Vue2.0 cannot be used.
Vue3.0 is compatible with most of the syntax in version 2.0 (how it was written before, and now it works), but there are also some destructive syntax updates, which should be paid special attention to:
1. The $on method on the vue instance (eventBusVue.prototype.$eventBus=new Vue (); this.$on (event name, callback) is no longer supported and can be replaced by a three-party plug-in. The following is the use of eventBus in vue2:
Vue.prototype.$eventBus = new Vue () component 1this.$on ('event name', callback) component 2this.$emit ('event name')
2. Remove filter option. The following is the use of filters in vue2:
{{msg | format}}
In the interpolation expression, the filter filter can no longer be used, but methods can be used instead of {{format (msg)}}.
3. Remove the .sync syntax (the .sync modifier can no longer be used in v-bind, and now its v-model syntax is merged). Here is the use of .sync in vue2
3. Project differences between vue2 and 3
It mainly looks at three positions:
Package.json
Main.js
App.vue
Package.json
First we can take a look at the package.json file, which shows in the dependencies configuration item that we are currently using version 3
"dependencies": {"core-js": "^ 3.6.5", "vue": "^ 3.2.25" / / version} main.js
Then open the main.js entry file and find that some changes have taken place in the instantiation of Vue, from the previous new keyword instantiation to the calling form of the createApp method.
How to write in vue2.x:
Import Vue from 'vue'import App from'. / App.vue'new Vue ({render: h = > h (App)}). $mount ('# app')
Vue3.x is written as follows:
Import {createApp} from 'vue'import App from'. / App.vue' / / Root component createApp (App) .mount ('# app') app.vue
Open app.vue and find that a unique root element is no longer mandatory in the single-file component of vue3.0
4. Combined API and optional API
Combinatorial api (Composition API) is an update of vue3 that has changed a lot for us developers.
Vue2 optional API,options API (pictured), Vue3 combined API, composition API (right):
Vue2 option API,options API:
Advantages:
Easy to understand, easy to use. Because each option (configuration item) has a fixed writing position (for example, the data is written to the data option, the operation method is written to the methods, etc.)
Disadvantages:
After the application is big, I believe everyone has encountered the dilemma of looking for code back and forth-horizontal jump.
Vue3 combined API, composition API:
Features:
All the things related to a specific function are maintained together, such as the responsive data related to function A, the methods of manipulating the data, etc., so that no matter how large the application is, all the related code of a function can be quickly located and easy to maintain.
If the function is complex and the amount of code is large, we can also carry out logical split processing.
Summary:
The origin of combined API. Because vue3 provides a new way to write code (the old way can also be used), in order to distinguish vue2, each of them is given a different name:
Vue2 optional API (option api) advantages: simple, each option does its own job; disadvantages: it is not convenient for functional reuse; functional code is scattered and maintenance code jumps across
Vue3 combined API (composition api) advantages: function code combination maintenance, convenient function reuse
4 、 setup
The setup function is a new component option that serves as the starting point (entry) for composite API in the component.
This cannot be used in setup. This points to undefined.
The setup function is executed only once when the component is initialized
The setup function executes before the beforeCreate lifecycle hook executes
Setup () {console.log ('setup....', this)}, beforeCreate () {console.log (' beforeCreate') / / it is later than setup}
Setup parameters:
When using setup, it accepts two parameters:
Props: props is an object that contains all the prop data passed by the parent component
Context: the context object contains attrs,slots and emit attributes
Return value
The return value of this function is an object, and the data and functions that need to be used in the template need to be declared in this object (if data of the same name is also defined in data (), then setup () prevails).
Name: {{name}}, monthly salary: {{salary}} say hello
Export default {setup () {console.log ('setup is executed, there is no this. The value of this is:', this) / / define the data and function const name = 'Xiao Wu' const salary = 18000 const say = () = > {console.log ('I am, name)} / / return the object, give the view return {msg, say}}, beforeCreate () {console.log ('beforeCreate is executed, where the value of this,this is:', this)}}
The props accepted in setup is responsive and will be updated in time when a new props is passed in. Because it is responsive, you cannot use ES6 deconstruction, which eliminates its responsiveness. Error code example, which causes props to no longer support responsiveness:
Export default com ({setup (props, context) {const {uname} = props console.log (uname)},})
Development we want to use deconstruction, but also maintain the responsiveness of props, is there a way to solve it? setup accepts the second parameter context, we said earlier that setup cannot access the most commonly used this object in Vue2, so context provides the three most commonly used properties in this: attrs, slot and emit, corresponding to the $attrs attribute in Vue2.x, slot slot and $emit emission event, respectively. And these properties are automatically synchronized with the latest values, so we get the latest values every time we use them.
5. Reactive, ref and toRefs
In vue2.x, the definition data is all in data, but Vue3.x can use reactive and ref for data definition.
How to choose between ref and reactive?
There are two ways to define responsive data:
The ref function (which can handle both simple and complex data) is often used to define simple data types as responsive data
When you modify (or get) a value in your code, you need to add .value.
When used in a template, .value can be omitted
Reactive function, often used to change complex data types to responsive data
Recommended usage:
Give priority to ref
If you know exactly what attributes are in the object, use reactive. For example, form data
Next, use the code to show the use of ref and reactive:
{{num}}
Name: {{user.uname}}
Age: {{user.age}}
Import {reactive, ref, toRefs} from "vue"; export default com ({setup () {const num = ref (0); const user = reactive ({uname: "vivian", age: 18}); setInterval () = > {num.value++; user.age++;}, 1000); return {year, user};},})
In the above code, we bind to the page through user.uname,user.age so it feels very tedious to write, can we directly deconstruct the properties in user and use it? The answer is that you can't structure user directly, which eliminates its responsiveness, which echoes the above statement that props cannot be deconstructed directly using ES6. Then what do we want to do with the deconstructed data? the solution is to use toRefs to define all attributes in the transformation response as responsive data, which is usually used for deconstruction | expand the reactive definition object to simplify our use in the template.
Format:
/ / responsive data: {attribute 1, attribute 2} let {attribute 1, attribute 2} = toRefs (responsive data)
The specific usage is as follows:
{{num}}
Name: {{uname}}
Age: {{age}}
Import {defineComponent, reactive, ref, toRefs} from "vue"; export default com ({setup () {const num = ref (0); const user = reactive ({uname: "vivian", age: 18}); setInterval () = > {num.value++; user.age++;}, 1000); return {year, / / use reRefs... toRefs (user),};},})
Enhanced structural assignment: while deconstructing objects, it retains the characteristics of responsiveness.
6. Vue3.0 lifecycle hook function
Before setup creates an instance
Before onBeforeMount mounts DOM
After onMount mounts DOM
Before BeforeUpdate updates the component
After updated updates the component
Before onBeforeUnmount uninstall and destroy
After unloading and destroying onUnmount
Setup () {onBeforeMount (() = > {console.log ('before DOM rendering', document.querySelector ('.container'))}) onMounted (() = > {console.log ('post-DOM rendering 1 documentation. QuerySelector (' .container'))})}
Vue3.x also adds hook functions onRenderTriggered and onRenderTricked for debugging. In addition, hooks in Vue3.x need to be imported from vue:
Import {defineComponent, onBeforeMount, onMounted, onBeforeUpdate,onUpdated,onBeforeUnmount, onUnmounted, onErrorCaptured, onRenderTracked,onRenderTriggered} from "vue" Export default defineComponent ({/ / beforeCreate and created are beforeCreate () {console.log ("--beforeCreate--")} of vue2, created () {console.log ("--created--")}, setup () {console.log ("--setup--") / / vue3.x life cycle is written in setup onBeforeMount (() = > {console.log ("--onBeforeMount--")} onMounted () = > {console.log ("--onMounted--") }) / / debug which data has changed onRenderTriggered ((event) = > {console.log ("--onRenderTriggered--", event)})},}); 7. Computed function defines calculation properties
Format:
Import {computed} from 'vue'const calculation attribute name = computed (() = > {return related calculation result})
Code example:
Name: {{name}}, company: {{company}}, monthly salary: {{salary}}, annual salary {{total}}
Monthly salary doubleimport {ref, computed} from 'vue'export default {name:' App' Setup () {/ / define responsive object const company = ref ('DiDi') const name = ref (' Xiao Wang') const salary = ref (18000) const double = () = > {salary.value * = 2 / / ref data to add. Value} / / define calculation attribute const total = computed (() = > 12 * salary.value) return {name, company, total Salary, double}
Summary:
The computed function in vue3 is similar to the computed option in vue2.
The input parameter of computed is a function
Function: generate new responsive data based on existing data.
Steps: import, define, export
Advanced usage of computed:
Format:
Const calculation attribute = computed ({get () {/ / when the value is automatically called}, set (val) {/ / when the value is automatically called, val will automatically pass in}})
Sample code:
Xiaohua, monthly salary: {{salary}}, annual salary: {{total}}
Annual salary:
Monthly salary double
/ / reactive: is the second way to declare responsive data besides ref import {ref Computed} from 'vue'export default {setup () {const salary = ref (18000) const double = () = > {salary.value * = 2 console.log (salary)} / / define calculation attribute: common writing: only use get / / const total = computed (() = > {/ / return stu.salary * 12 / /}) / / define calculation Attribute: higher order: get + set const total = computed ({get () {return salary.value * 12}) Set (val) {/ / sets the value of the calculation property Will be called automatically, passing in val console.log ('value to be set...', val) salary.value = val/12}}) return {double, salary, total}}
Summary:
Two uses of calculation attributes
Pass a function to computed, and the return value is the value of the calculation attribute.
Pass an object to computed, get gets the value of the calculation property, and set listens for the change of the calculation property
Bind the calculation properties in v-model:
8. Watch function
The callback logic is executed based on changes in responsive data, which is exactly the same as the application scenario of watch in vue2.
Steps:
Import import {watch} from 'vue'
Turn on listening. Execute the watch function in the setup function to turn on the monitoring of responsive data
The watch function takes three general arguments watch (source, callback, [options])
The first parameter has three values:
Object, responsive data to listen for
Array, each element is responsive data
Function that returns the responsive data that you want to listen for changes
The second parameter is the callback function to be executed after the responsive data changes
The third parameter is an object in which you can configure whether to enable immediate execution or deep monitoring
{{stu}}, {{salary}} do
Import {reactive, watch, ref} from 'vue'export default {setup () {const salary = ref (10000) const stu = reactive ({address: {city:' wuhan'}}) / / 1. Listening-single data watch (salary, (newVal, oldVal) = > {console.log ('listening single data', newVal, oldVal)}) / / listening-single data watch (stu, (newVal, oldVal) = > {console.log ('listening single data', newVal) OldVal)}) / / listen-multiple data watch ([stu, salary], (newVal, oldVal) = > {console.log ('listening for multiple data', newVal, oldVal)}) / / A property of the listening object watch (() = > stu.address, (newVal) OldVal) = > {console.log ('the first argument is a function', newVal, oldVal)}, {deep: true, immediate: true}) / / Test button Modify data const doSome = () = > {salary.value + = 1 stu.address.city =''} return {stu, salary, doSome}} so far, I believe you have a deeper understanding of "how to use the new features of Vue3.0". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
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.