In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
Editor to share with you the vue3 document combing example analysis, I believe that most people do not know much about it, so share this article for your reference, I hope you will learn a lot after reading this article, let's go to understand it!
1. Setup
Combined API:
The setup option should be a function
The setup option function takes two parameters: props and context
The setup option function needs to return what is to be exposed to the component
Setup needs to be returned using return before it can be used by components, including data and methods
1. The first parameter in the setup function-- props
The props in the setup function is responsive and will be updated when a new prop is passed in
Export default {props: {title: String}, setup (props) {console.log (props.title)}}
However, because props is responsive, you cannot use ES6 deconstruction because it eliminates the responsiveness of prop.
If you need to deconstruct prop, you can do this safely by using toRefs in the setup function.
Import {toRefs} from 'vue'setup (props) {const {title} = toRefs (props) console.log (title.value)} 2. Contextcontext
The second parameter in the setup function, the contextcontext context, is a normal JavaScript object that exposes the property of the three components.
Xport default {setup (props, context) {/ / Attribute (non-responsive object) console.log (context.attrs) / slot (non-responsive object) console.log (context.slots) / / trigger event (method) console.log (context.emit)}}
Context is an ordinary JavaScript object, that is, it is not responsive, which means that you can safely deconstruct context using ES6
Export default {setup (props, {attrs, slots, emit}) {...}} II. Return value of setup function return value of 1.setup function-- object
If setup returns an object, you can access the property of that object in the template of the component like the props property passed to setup:
{{readersNumber}} {{book.title}} import {ref, reactive} from 'vue' export default {setup () {const readersNumber = ref (0) const book = reactive ({title:' Vue 3 Guide'}) / / expose to template return {readersNumber, book}}
Note: the refs returned from setup is unlocked automatically when accessed in the template, so .value should not be used in the template.
Third, the responsive system API1. Reactive
Reactive () takes a normal object and returns a responsive proxy for that normal object. Equivalent to 2.x Vue.observable ()
Const obj = reactive ({count: 0})
The responsive transformation is "deep": it affects all nested properties within the object. Based on the Proxy implementation of ES2015, the returned proxy object is not equal to the original object. It is recommended that you use only proxy objects and avoid relying on the original objects.
{state.count} import {reactive} from 'vue'export default {setup () {/ / state is now a responsive state const state = reactive ({count: 0,})} 2. Ref
Accepts a parameter value and returns a responsive and mutable ref object. The ref object has a single property. Value that points to the internal value.
Const count = ref (0) console.log (count.value) / / 0count.value++console.log (count.value) / / 1
If the object passed in the ref is an object, the reactive method is called for a deep response transformation.
Access to the template:
When ref is returned as a property of the rendering context (that is, in the object returned by setup ()) and used in the template, it automatically unlocks the lock, eliminating the need to write additional .value in the template:
{{count}} export default {setup () {return {count: ref (0),}},}
Access as a property of a responsive object:
When ref is accessed or modified as the property of a reactive object, the value value is also automatically unlocked and behaves like a normal property:
Const count = ref (0) const state = reactive ({count,}) console.log (state.count) / / 0state.count = 1console.log (count.value) / / 1
Note: if a new ref is assigned to an existing ref, the old ref will be replaced:
Const otherCount = ref (2) state.count = otherCountconsole.log (state.count) / / 2console.log (count.value) / / 1
Note: ref will release the lock only when it is nested in reactive Object. When you access ref from a native collection class such as Array or Map, the lock is not automatically released:
Const arr = reactive ([ref (0)]) / / .valueconsole.log (arr [0] .value) const map = reactive (new Map ([[foo', ref (0)])) / / .valueconsole.log (map.get ('foo') .valueconsole.log) is needed here.
Type definition:
Interface Ref {value: t} function ref (value: t): Ref
Sometimes we may need to do a more complex type annotation for ref. We can override the default derivation by passing generic parameters when calling ref:
Type of const foo = ref ('foo') / / foo: Reffoo.value = 123 / / can pass! 3. Computed
There are two ways to use responsive computed API:
(1) pass in a getter function and return a ref object that cannot be modified manually by default.
Const count = ref (1) const plusOne = computed (() = > count.value + 1) console.log (plusOne.value) / / 2plusOne.valuevaluation + / / error!
(2) pass in an object with get and set functions to create a calculation state that can be modified manually.
Const count = ref (1) const plusOne = computed ({get: () = > count.value + 1, set: (val) = > {count.value = val-1},}) plusOne.value = 1console.log (count.value) / / 0
Type definition:
/ / read-only function computed (getter: () = > T): Readonly// changeable function computed (options: {get: () = > T set: (value: t) = > void}): Ref4. Readonly
Pass in an object (responsive or normal) or ref and return a read-only proxy of the original object. A read-only proxy is "deep", and any nested properties within the object are read-only.
Const original = reactive ({count: 0}) const copy = readonly (original) watchEffect (() = > {/ / dependent tracking console.log (copy.count)}) / / changes on original trigger snooping original.count++// on copy that cannot modify copy and will be warned copy.count++ / / warningtrace 5. WatchEffect
Execute a function passed in immediately, track its dependency responsively, and rerun the function if it depends on a change.
Const count = ref (0) watchEffect (() = > console.log (count.value)) / /-> print out 0setTimeout (() = > {count.value++ / /-> print out 1}, 100) 5.1 stop listening
When watchEffect is called in a component's setup () function or lifecycle hook, the listener is linked to the component's lifecycle and automatically stops when the component is unloaded.
In some cases, you can also explicitly call the return value to stop listening:
Const stop = watchEffect (() = > {/ *... * /}) / / after stop () 5.2 clear side effects
Sometimes the side effect function performs some asynchronous side effects that need to be cleared when it fails (that is, the state has changed before completion). So a function that listens for side effects can take an onInvalidate function as an input parameter to register callbacks when cleanup fails. This failure callback is triggered when the following occurs:
When the side effects are about to be re-executed,
The listener is stopped (if watchEffect is used in the setup () or lifecycle hook function, when the component is unloaded)
WatchEffect ((onInvalidate) = > {const token = performAsyncOperation (id.value) onInvalidate () = > {/ / Asynchronous operation before id changes or stops listening / / cancels)})
We register the invalid callback by passing in a function instead of returning it from the callback (as in React useEffect) because the return value is important for asynchronous error handling.
When performing a data request, the side effect function is often an asynchronous function:
Const data = ref (null) watchEffect (async () = > {data.value = await fetchData (props.id)})
We know that asynchronous functions implicitly return a Promise, but the cleanup function must be registered before the Promise is resolve. In addition, Vue relies on the returned Promise to automatically handle potential errors on the Promise chain.
5.3 side effect refresh time
Vue's responsive system caches side-effect functions and flushes them asynchronously to avoid unnecessary repeated calls caused by multiple state changes in the same tick. In the core implementation, the update function of the component is also a side effect of being listened on. When a user-defined side effect function is queued, it is executed after all components have been updated:
{{count}} export default {setup () {const count = ref (0) watchEffect (() = > {console.log (count.value)}) return {count,}},}
In this example:
Count will print out synchronously during the initial run
When you change the count, side effects are performed after the component is updated.
Note that the initialization run is performed before the component mounted. So, if you want to access DOM (or template ref) when writing side-effect functions, do so in the onMounted hook:
OnMounted (() = > {watchEffect (() = > {/ / you can access DOM or template refs})})
If the side effect needs to be synchronized or rerun before the component update, we can pass an object with the flush property as an option (the default is' post'):
/ / run watchEffect (() = > {/ *... * /}, {flush: 'sync',}) / / perform watchEffect (() = > {/ *... * /}, {flush:' pre',}) 5.4 listener debugging before component update
The onTrack and onTrigger options can be used to debug the behavior of a listener.
OnTrack is called when a reactive object property or a ref is tracked as a dependency
OnTrigger is called when a side effect is triggered due to a dependency change
Both callbacks will receive a debugger event that contains information about the dependencies. It is recommended that you write a debugger statement in the following callback to check for dependencies:
WatchEffect (() = > {/ * content of side effects * /}, {onTrigger (e) {debugger},})
OnTrack and onTrigger only take effect in development mode.
Type definition:
Function watchEffect (effect: (onInvalidate: InvalidateCbRegistrator) = > void, options?: WatchEffectOptions): StopHandleinterface WatchEffectOptions {flush?: 'pre' |' post' | 'sync' onTrack?: (event: DebuggerEvent) = > void onTrigger?: (event: DebuggerEvent) = > void} interface DebuggerEvent {effect: ReactiveEffect target: any type: OperationTypes key: string | symbol | undefined} type InvalidateCbRegistrator = (invalidate: () = > void) = > voidtype StopHandle = () = > void6. Watch
Watch API is completely equivalent to 2.x this.$watch (and the corresponding options in watch). Watch needs to listen for specific data sources and perform side effects in callback functions. The default is lazy execution, that is, callbacks are performed only when the listening source changes.
Comparing watchEffect,watch allows us to:
Side effects of lazy execution
Be more clear about which state changes trigger listeners to rerun side effects
Access the value before and after the listening state changes.
Listen for a single data source
The data source for the listener can be a getter function with a return value, or it can be ref:
/ / listen on a getterconst state = reactive ({count: 0}) watch (() = > state.count, (count, prevCount) = > {/ *... * /}) / / listen directly on a refconst count = ref (0) watch (count, (count, prevCount) = > {/ *... * /}) 6.1 listen on multiple data sources
Watcher can also use arrays to listen for multiple sources at the same time:
Watch ([fooRef, barRef], ([foo, bar], [prevFoo, prevBar]) = > {/ *... * /}) 6.2 behavior of sharing with watchEffect
Watch and watchEffect have the same behavior in stopping listening, clearing side effects (accordingly, onInvalidate is passed in as the third parameter of the callback), side effects refresh timing and listener debugging.
Type definition:
/ / listening single data source function watch (source: WatcherSource, callback: (value: T, oldValue: T, onInvalidate: InvalidateCbRegistrator) = > void, options?: WatchOptions): StopHandle// snooping multiple data sources function watch (sources: t callback: (values: MapSources, oldValues: MapSources, onInvalidate: InvalidateCbRegistrator) = > void, options?: WatchOptions): StopHandletype WatcherSource = Ref | () = > T) type MapSources = {[K in keyof T]: t [K] extends WatcherSource? V: never} / / Common properties please check the type definition of `watchEffect` interface WatchOptions extends WatchEffectOptions {immediate?: boolean / / default: false deep?: boolean} above is all the content of this article "sample Analysis of documentation in vue3". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
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.