In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains "how to get started with Vue3". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to get started with Vue3 quickly".
Comparison between Vue2 and Vue3
Unfriendly support for TypeScript (all properties are placed on this objects, so it is difficult to knock down the data type of the component)
A large number of API is mounted on the prototype of the Vue object, so it is difficult to implement TreeShaking.
Architecture level is not friendly to cross-platform dom rendering development support.
CompositionAPI . Love ReactHook inspiration
More convenient support for jsx
Multiple root tags are supported for Template in Vue 3, but not in Vue 2
Rewrite the virtual DOM and optimize the compilation of the template.
1. Setup function
The setup () function is a new property in vue3 that is provided specifically for components. It provides a unified entrance for us to use the new Composition API feature of vue3. The setup function will be executed after beforeCreate and before created. Vue3 also cancels these two hooks and replaces it with setup. This function is equivalent to a life cycle function. All the past data,methods,watch in vue are written in the setup () function with the corresponding new api.
Setup (props, context) {context.attrs context.slots context.parent context.root context.emit context.refs return {}}
Props: used to receive props data
Context is used to define the context, and the context object contains some useful properties that can only be accessed through this in vue 2.x. This is not accessible in the setup () function. It is a undefined.
Return value: return {}, return responsive data, functions to be used in the template
2. Reactive function
The reactive () function receives a normal object and returns a responsive data object. It is also easy to use the created responsive data. After it is created, you can return it in setup and call it directly in template.
{{name}} / / test import {defineComponent, reactive, ref, toRefs} from 'vue'; export default defineComponent ({setup (props, context) {let state = reactive ({name:' test'}); return state}}); third, ref () function
The ref () function is used to create a responsive data object based on a given value. The return value of the ref () function call is an object, which contains only one value attribute. Value is needed to access the ref function only within the setup function.
{{count}} / / 10 import {defineComponent, ref} from 'vue'; export default defineComponent ({setup () {const count = ref (10) / / to get the value defined in ref through the value attribute console.log (count.value); return {count})
Access the responsive data created by ref in the reactive object
{{count}}-{{t}} / 10-100 import {defineComponent, reactive, ref, toRefs} from 'vue'; export default defineComponent ({setup () {const count = ref (10) const obj = reactive ({t: 100, count}) / / when obtaining the value of ref through reactive, the .value attribute console.log (obj.count) is not required Return {... toRefs (obj)}}); IV. IsRef () function
IsRef () is used to determine whether a value is an object created by ref ().
Import {defineComponent, isRef, ref} from 'vue'; export default defineComponent ({setup (props, context) {const name: string =' vue' const age = ref (18) console.log (isRef (age)); / / true console.log (isRef (name)); / / false return {age, name}); 5. ToRefs () function
The toRefs () function can convert the responsive object created by reactive () into a normal object, but each attribute node on this object is responsive data of type ref ().
{{name}} / / test {{age}} / / 18 import {defineComponent, reactive, ref, toRefs} from 'vue'; export default defineComponent ({setup (props, context) {let state = reactive ({name:' test'}); const age = ref (18) return {... toRefs (state), age}); computed ()
This function is used to create computational properties, and as in the past, the value it returns is a ref object. You can pass a method or an object that contains set () and get () methods
6.1 create read-only calculation properties
Import {computed, defineComponent, ref} from 'vue'; export default defineComponent ({setup (props, context) {const age = ref (18) / / create a responsive calculation property readOnlyAge based on the value of age, which automatically calculates and returns a new ref const readOnlyAge = computed (() = > age.value++) / / 19 return {age, readOnlyAge} based on the dependent ref)
6.2. create a readable and writable calculation attribute through the set () and get () methods
Import {computed, defineComponent, ref} from 'vue' Export default defineComponent ({setup (props, context) {const age = ref (18) const computedAge = computed ({get: () = > age.value + 1, set: value = > age.value + value}) / / the operation of assigning values to calculated attributes triggers the set function, and when the set function is triggered, the value of age is updated age.value = 100return {age, computedAge}}) 7. Watch () function
The watch function is used to listen for specific data sources and to perform side effects in callback functions. The default is lazy execution, that is, callbacks are performed only when the listening source data changes.
7.1 listening for data sources declared with reactive
Import {computed, defineComponent, reactive, toRefs, watch} from 'vue'; interface Person {name: string, age: number} export default defineComponent ({setup (props, context) {const state = reactive ({name:' vue', age: 10}) watch (() = > state.age, (age, preAge) = > {console.log (age); / / 100console.log (preAge) / / 10}) / / the callback of watch will be triggered when age is modified, and the value before and after the change will be printed: state.age = 100 return {... toRefs (state)}})
7.2 listening for data sources declared with ref
Import {defineComponent, ref, watch} from 'vue'; interface Person {name: string, age: number} export default defineComponent ({setup (props, context) {const age = ref (10); watch (age, () = > console.log (age.value)); / / 100 / / watch callback is triggered when age is modified, and the changed value age.value = 100return {age}} is printed)
7.3 listen for multiple values at the same time
Import {computed, defineComponent, reactive, toRefs, watch} from 'vue'; interface Person {name: string, age: number} export default defineComponent ({setup (props, context) {const state = reactive ({name:' vue', age: 10}) watch ([() = > state.age, () = > state.name], ([newName, newAge], [oldName, oldAge]) = > {console.log (newName); console.log (newAge) Console.log (oldName); console.log (oldAge);}) / / the callback of watch will be triggered when the age is modified, and the values before and after the change will be printed. Note that changing one of the values will execute the callback of watch state.age = 100state.name = 'vue3' return {. ToRefs (state)})
7.4 stop stops snooping
The watch monitor created within the setup () function automatically stops when the current component is destroyed. If you want to explicitly stop a monitor, you can call the return value of the watch () function, with the following syntax:
Import {set} from 'lodash'; import {computed, defineComponent, reactive, toRefs, watch} from' vue' Interface Person {name: string, age: number} export default defineComponent ({setup (props, context) {const state = reactive ({name: 'vue', age: 10}) const stop = watch ([() = > state.age, () = > state.name], ([newName, newAge], [oldName, oldAge]) = > {console.log (newName); console.log (newAge); console.log (oldName) Console.log (oldAge) }) / / the callback of watch will be triggered when age is modified, and the values before and after the change will be printed. Note that changing one of the values will execute the callback of watch state.age = 100state.name = 'vue3' setTimeout () = > {stop () / / when modified at this time. Will not trigger watch callback state.age = 1000 state.name = 'vue3-'}, 1000) / 1 second later cancel the listening of watch return {... toRefs (state)}}) 8. LifeCycle Hooks (New late Life)
The new version of the lifecycle function can be imported into components on demand and can only be used in the setup () function, but it can also be customized in setup and used in setup
Import {set} from 'lodash'; import {defineComponent, onBeforeMount, onBeforeUnmount, onBeforeUpdate, onErrorCaptured, onMounted, onUnmounted, onUpdated} from' vue' Export default defineComponent ({setup (props) Context) {onBeforeMount (() = > {console.log ('console.log (' mountedstones')}) onMounted (() = > {console.log ('mounteddates')}) onBeforeUpdate (() = > {console.log ('updateddates')}) onBeforeUnmount (() = > {console.log () onUnmounted (() = > {console.log ('unmounted ships')}) onErrorCaptured (() = > {console.log ('errorCapturedships')}) return {}}) IX. Template refs
To return the real dom element through refs, which is the same as react, to get a reference to the element or component instance in the template, we can declare a ref in setup () as usual and return it
As usual, write the name of ref in html
Define a ref in steup
Return the instance of ref in steup
The RefImpl object of ref can be obtained in onMounted, and the real dom can be obtained through .value
1111 import {set} from 'lodash'; import {defineComponent, onMounted, ref} from' vue'; export default defineComponent ({setup (props, context) {/ / get real dom const elmRefs = ref (null); onMounted (() = > {console.log (elmRefs.value); / / get a RefImpl object and access data through .value}) return {elmRefs}}) Global configuration of vue
Through the configuration of config on the vue instance, contains the objects that are configured globally by the Vue application. You can modify the properties listed below before mounting the application:
Const app = Vue.createApp ({}) app.config = {...}
Assign handlers to uncaptured errors during component rendering functions and watchers. Errors and application instances will call handlers
App.config.errorHandler = (err, vm, info) = > {}
Global properties that can be accessed in any instance of a component within the application, the properties of the component will have priority. This can replace the Vue 2.xVue.prototype extension:
Const app = Vue.createApp ({}) app.config.globalProperties.$http = 'xxxxxxxxs'
The information configured in the global globalProperties can be obtained through getCurrentInstance () in the component, the getCurrentInstance method gets the instance of the current component, and then the current context is obtained through the ctx property, so that we can use router and vuex in the setup, through which we can manipulate variables, global properties, component properties, and so on.
Setup () {const {ctx} = getCurrentInstance (); ctx.$http} 11, Suspense components
Before we begin to introduce the Suspense components of Vue, it is necessary to take a look at the Suspense components of React, because their functions are similar.
React.lazy accepts a function that requires a dynamic call to import (). It must return a Promise, which requires a React component of a default export to resolve.
Import React, {Suspense} from 'react'; const myComponent = React.lazy (() = > import ('. / Component')); function MyComponent () {return ();}
Vue3 has also added a defineAsyncComponent function with similar functionality to React.lazy to deal with dynamically introduced components. DefineAsyncComponent can accept factory functions that return promises. When you retrieve the component definition from the server, you should call Promise's parsing callback. You can also call reject (reason) to indicate that the load has failed
Import {defineAsyncComponent} from 'vue' const AsyncComp = defineAsyncComponent (() = > import ('. / components/AsyncComponent.vue')) app.component ('async-component', AsyncComp)
Vue3 has also added Suspense components:
Loading... Import {defineComponent, defineAsyncComponent} from "vue"; const MyComponent = defineAsyncComponent (() = > import ('. / Component')); export default defineComponent ({components: {MyComponent}, setup () {return {}}) XII, vue 3.x full component template structure
A completed vue 3.x complete component template structure contains: component name, props, components, setup (hooks, computed, watch, methods, etc.)
{{name}}
{{count}} Test button {{item.name}} import {computed, defineComponent, getCurrentInstance, onMounted, PropType, reactive, ref, toRefs} from 'vue' Interface IState {count: 0, name: string, list: Array} export default defineComponent ({name: 'demo', / / parent component passes child component parameters props: {name: {type: String as PropType, default:' vue3.x'}, list: {type: Array as PropType, default: () = > []}} Components: {/ TODO component registration}, emits: ["emits-name"], / / to prompt setup (props, context) {console.log (props.name) console.log (props.list) const state = reactive ({name: 'vue 3.0 component', count: 0, list: [{name: 'vue' Id: 1}, {name: 'vuex', id: 2}]}) const a = computed (() = > state.name) onMounted (() = > {}) function handleClick () {state.count + + / / call the parent component's method context.emit (' emits-name' State.count)} return {... toRefs (state), handleClick}}) {{name}}
{{count}} Test button {{item.name}} import {computed, defineComponent, getCurrentInstance, onMounted, PropType, reactive, ref, toRefs} from 'vue' Interface IState {count: 0, name: string, list: Array} export default defineComponent ({name: 'demo', / / parent component passes child component parameters props: {name: {type: String as PropType, default:' vue3.x'}, list: {type: Array as PropType, default: () = > []}} Components: {/ TODO component registration}, emits: ["emits-name"], / / to prompt setup (props, context) {console.log (props.name) console.log (props.list) const state = reactive ({name: 'vue 3.0 component', count: 0, list: [{name: 'vue' Id: 1}, {name: 'vuex', id: 2}]}) const a = computed (() = > state.name) onMounted (() = > {}) function handleClick () {state.count + + / / call the parent component's method context.emit (' emits-name' State.count)} return {... toRefs (state), handleClick}}) Thank you for your reading, the above is the content of "how to get started with Vue3 quickly". After the study of this article, I believe you have a deeper understanding of how to quickly get started with Vue3, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
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.