Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to get started with vue3 quickly

2025-01-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

Most people do not understand the knowledge points of this "how to get started with vue3" article, so the editor summarizes the following content, detailed content, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "how to get started with vue3" article.

Global API and application API

A new concept of vue3 that returns an application instance that provides an application context. The entire component tree mounted by the application instance shares the same context:

Const app = createApp (App); app.use (store) .use (router) .mount ("# app")

Vue2:

New Vue ({router, store, render: (h) = > h (App),}). $mount ("# app")

Then used to use Vue. Those API are changed to use this application example app.:

Vue2vue3Vue.componentapp.componentapp.configapp.configapp.directiveapp.directiveapp.mixinapp.mixinapp.useapp.use

Other API, such as nextTick, h, etc. are used directly from the vue structure:

Import {createApp, h, nextTick} from 'vue'

Composition API

Tips

This is no longer used in vue3

The vue3 component does not need a root tag, but there will be a warning Extraneous non-props attributes

It is recommended to use single-file component, and the following implementation code is single-file component.

Setup

This is so important that vue3 uses this function as an entry point. Receive two parameters, props and context. The function will be executed before beforeCreate and created, which can be said to replace beforeCreate and created as the new life cycle. The new composition API is written in the setup function.

Props is the props,context of vue2 and provides attrs, slots, emit and so on. By return an object, the responsive data is exposed to template, which is equivalent to the data of vue2. The difference is that the function is also exposed to template in this way:

{{msg}} import {defineComponent, ref} from "vue"; export default defineComponent ({name: "HelloWorld", props: {msg: String,}, setup (props) {console.log (props.msg); let isRef = ref ("is ref"); const test = () = > {console.log (isRef.value);}; return {isRef, test,};},}) Single file component

Vue3 also provides a single file component (recommended). Add setup to script and the code inside will be compiled into setup functions. A few more important points:

The binding at the top level is exposed to the template

The declared top-level bindings (including variables, function declarations, and content introduced by import) can be used directly in templates, such as responsive data, components, and so on:

{{msg}} {{isRef}} import MyComponent from'. / MyComponent.vue'import {ref} from "vue"; const msg = "msg"; const isRef = ref ("); function test () {console.log (isRef.value);}

With single-file components, the use of some properties also needs to be changed, and of course there are other alternatives to API:

Properties correspond to props and emitsdefineProps and defineEmitsref or $parentdefineExposeslots and attrsuseSlots and useAttrs () ref

Accept an internal value and return a responsive and mutable ref object. To access the ref function inside the setup function, you need to add .value. If you want to add a type, you need to use generics. If you do not add a type, you will infer the type, or you may not give an initial value, then it is any and undefined:

Const ref1 = ref (1); const ref2 = ref (2); const ref3 = ref1.value;// is not responsive, equivalent to the variable const ref4 = ref (); / / refs.value is undefinedref2.value = 5. Value

/ / it is not recommended that reactive also handle const ref1 = ref ({a: 10,}); / / uncertain type const ref3 = ref (); ref3.value = 1 type Obj2 ref3.value = ""; / / Array objects, ts type declaration, with generic type Obj1 = {c: string}; type Obj2 = {b: string; c: Obj1 [];} Const ref2 = ref ([{b: ", c: [{c:"}],},]); reactive

Used to declare responsive objects, and types are added through generics:

Type Obj = {a: number; b: string;}; let obj = reactive ({a: 10, b: "",}); let state = reactive ({a: 10, b: "",})

Reactive will unpack all deep refs while maintaining the responsiveness of ref, and when ref is assigned to reactive's property, ref will also be automatically unpackaged. To put it simply, the value of ref is responsive to the value of reactive.

Const count = ref (1) const obj = reactive ({count}) / / ref will be unpackaged console.log (obj.count = count.value) / / true// it will update `obj.count`count.value + + console.log (count.value) / / 2console.log (obj.count) / / 2console.log / it will also update `count`count` refobj.count++console.log (obj.count) / / 3console.log (count.value) / / 3pm / same effect as above const count = ref (1) const obj = reactive ({}) obj.count = countconsole.log (obj.count) / / 1console.log (obj.count = = count.value) / / truetoRef

Create a new ref for a property on a source responsive object, which is created by reactive, and maintain a responsive connection to its source property:

Const state = reactive ({foo: 1, bar: 2}) const fooRef = toRef (state, 'foo') fooRef.value++console.log (state.foo) / / 2state.foo++console.log (fooRef.value) / / 3toRefs

Converts a responsive object to a normal object, where each property of the resulting object is a ref that points to the corresponding property of the original object:

Const state = reactive ({foo: 1, bar: 2}) const stateAsRefs = toRefs (state) / * Type of stateAsRefs: {foo: Ref, bar: Ref} * / ref and the original property have been "linked" state.foo++console.log (stateAsRefs.foo.value) / / 2stateAsRefs.foo.value++console.log (state.foo) / / 3

ToRef and toRefs can be useful to expand some responsive object structures and look at them when they are useful.

Watch

Watch accepts two parameters, the first parameter can be a function with return or a ref, the second parameter is the same function as vue2, and there can be many watch:

/ / General ref does not use this method let count = ref (0); watch (() = > count.value, (val, old) = > {console.log (old, val);}); / / single ref recommended watch (count, (val, old) = > {console.log (old, val);}); / / listening on reactive object let state = reactive ({count: 0}) / / function parameters must be specific to a certain value, if () = > state is invalid, or add {deep: true} watch (() = > state.count, (val, old) = > {console.log (old, val);}); / / add {deep: true} watch (() = > state, (val, old) = > {console.log (old, val);}, {deep: true}) / / listen to the whole object with the same new and old values, or use lodash.cloneDeep to make a deep copy / / state to () = > _ .cloneDeep (state) watch (state, (val, old) = > {console.log (old.count, val.count);})

You can also listen to multiple parameters at the same time, using an array for the two parameters, or individual or individual:

Const state = reactive ({count: 1}); const count = ref (0); / / listen to an array watch ([() = > state.count, count], ([newState, newCount], [oldState, oldCount]) = > {console.log ("new:", newState, newCount); console.log ("old:", oldState, oldCount);})

Inertia has been mentioned all the time on the official website, which means whether to add immediate: true, which will be executed after initialization.

WatchEffect

It "executes" a function passed in immediately, responsively tracks its dependencies, and reruns the function when its dependency changes:

Const state = reactive ({count: 1}); const count = ref (0); watchEffect () = > {if (state.count > 3) {count.value++;}}); watchEffect (() = > console.log (count.value))

As for watch and watchEffect sharing to stop listening, remove side effects (accordingly, onInvalidate will be passed in as the third parameter of the callback), side effects refresh timing, and listener debugging behavior should be examined carefully later.

Computed

Since vue2, many people can not tell when to use computed and when to use watch,computed is mainly used to declare two or more dependent data, that is, a variable is based on multiple data to judge, with computed, single with watch. Not to mention the difference in syntax, the common syntax of vue3 computed is a function with return, or there can be more than one at the same time:

Let count = ref (0); let page = ref (0); let pg = computed (() = > {return count.value + page.value;})

Note that the variables declared by computed (pg) cannot be modified directly (read-only). Like vue2, there are get and set functions (readable and writable).

DefineProps 、 defineEmits

DefineProps and defineEmits API must be used in a single file component to declare props and emits, which can be considered syntactic sugar. The parent component still passes the value as before, and the child component receives:

/ / parent component import {ref} from "vue"; import HelloWorld from "@ / components/HelloWorld.vue"; let msg = ref ("is parent"); const change = (val: string) = > {msg.value = val;}; / / subcomponent {{msg}} emitimport {defineProps, defineEmits} from "vue"; const props = defineProps ({msg: String,}); console.log (props.msg); const emit = defineEmits (["change"]) Const change = () = > {emit ("change", "is son");}; / / set the default value defineProps ({msg: {type: Number, default: 100,},})

Template can use msg directly, and if you want to call it, you have to props.msg.

WithDefaults

DefineProps can only limit the type and does not provide a default value (here, there should be no default value for the API that limits the use of ts). To solve this problem, withDefaults compiler macros are provided:

Type Porps = {msg: string;}; const props = withDefaults (defineProps (), {msg: "default",})

WithDefaults receives two parameters, the first of which is the generics of the defineProps plus props field, and the second is the default value, or it can be left unset.

You can also monitor props:

Watch (() = > props.msg, (val) = > {console.log (val);}); this.$refs

In many cases, vue2 needs to be used in this api,vue3. In order to get a reference to an element or component instance in the template, we can declare ref as usual, expose the root in the rendering context, and bind it to div as its ref through ref= "root". In the virtual DOM patch algorithm, if the ref key of VNode corresponds to the ref in the rendering context, the corresponding element or component instance of VNode is assigned to the value of that ref. This is performed during virtual DOM mounting / patching, so template references are only assigned after the initial rendering.

TestReflet testRef = ref (null); onMounted (() = > {/ / DOM element will be assigned to ref console.log (testRef.value) after initial rendering; / / testRef}); nextTick

Use the same as vue2:

NextTick (() = > {console.log (testRef.value);})

You can also use the function await of async as provided on the official website:

Let testRef = ref (null); const nextTickFn = async () = > {await nextTick (); console.log (testRef.value);}; nextTickFn (); defineExpose

Vue2 sometimes uses this.$refs to call functions or variables of subcomponents. Single-file components are turned off by default, so single-file components are exposed with defineExpose compiler macros:

/ / parent component import {nextTick, ref} from "vue"; import HelloWorld from "@ / components/HelloWorld.vue"; let sonRef = ref (); nextTick () = > {sonRef.value.sonFn (); console.log (sonRef.value.sonRef);}); / / subcomponent let sonRef = ref ("is son"); const sonFn = () = > {console.log ("is son fn");}; defineExpose ({sonFn, sonRef})

Vue2's this.$parent is implemented by itself in the single file component, but the official code is not given directly:

/ / parent component const parentRef = ref ("is parent ref"); const parentFn = () = > {console.log ("is parent fn");}; defineExpose ({parentRef, parentFn,}); / / Child component let parent = getCurrentInstance (); console.log (parent?.parent?.exposed?.parentRef.value); parent?.parent?.exposed?.parentFn ()

New component

Teleport

The official website introduces a lot. The biggest function of this component is to make the component detach from the fixed component location and can be mounted in the logically optimal location. All other uses are the same as the component, only the location is changed:

The mounted elements are parsed from top to bottom, the first to elements, tags, class, id, and so on. General use will not be casual, will use the id element or body.

Suspense

Suspense is an experimental new feature, and officials also say it should not be used in production environments. The main purpose is to allow the component asynchronous processing wait process to be promoted to the component tree.

The top-level await in the single-file component mentions that async setup () must be used in combination with Suspense, and Suspense is still an experimental feature. We plan to develop and provide documentation in a future release.

So the code implementation that is not a single file component is not given here.

Life cycle

The life cycle is still the same as before, except that on,destroy is added in front of it and becomes unmount. Setup will be executed before beforeCreate and created, replacing beforeCreate and created.

BeforeCreate-- > beforeCreate

Created-- > setup

BeforeMount-- > onBeforeMount

Mounted-- > onMounted

BeforeUpdate-- > onBeforeUpdate

Updated-- > onUpdated

BeforeDestroy-- > onBeforeUnmount

Destroyed-- > onUnmount

Use:

OnMounted (() = > {console.log ("mounted");})

I tried it, but I could write more than one.

In fact, it is not necessary to remember all the API added or deleted by vue3. If some API is found to be ineffective, check the official website again. Of course, you have to write down the basic API.

The above is about the content of this article on "how to get started with vue3 quickly". I believe we all have a certain understanding. I hope the content shared by the editor will be helpful to you. If you want to know more related knowledge, please pay attention to 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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report