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 use TypeScript in Vue3

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

Share

Shulou(Shulou.com)05/31 Report--

This article mainly introduces the relevant knowledge of "how to use TypeScript in Vue3". The editor shows you the operation process through an actual case. The operation method is simple, fast and practical. I hope this article "how to use TypeScript in Vue3" can help you solve the problem.

How do I declare a type of a field named enumeration?

By design, the type field should be an enumerated value and should not be set at will by the caller.

The following is the enumerated declaration of Type, with a total of six fields.

Enum Type {primary = "primary", success = "success", warning = "warning", warn = "warn", / / warning alias danger = "danger", info = "info",}

There are two keywords for declaring types in TypeScript, interface and type, which are slightly different when declaring fields of key indeterminate types.

Use type to declare:

Type ColorConfig = {[key in Type]: Colors;}

Using interface can only be done like this:

Interface ColorConfig {[key: string]: Colors;}

Because the index of interface can only be a base type, and type aliases are not allowed. The index of type can be a compound type.

How does Vue 3 get element instances?

In vue3, the logic of the component can be placed in the setup function, but there is no this in setup, so the use of this.$refs in vue2 cannot be used in vue3.

The new usage is:

Add a ref attribute to the element.

Declare a variable with the same name as the element ref in setup.

Return the ref variable as a property of the same name in the return object of setup.

Access the ref variable, which is both an element instance, during the onMounted life cycle.

Step one:

Step 2:

Const point = ref (null)

Note that the type should be filled in HTMLDivElement so that you can enjoy type inference.

Step 3:

Return {point}

This step is necessary, and if the returned object does not contain this property of the same name, the ref object accessed in the onMounted will be null.

Step 4:

OnMounted (() = > {if (point?.value) {/ / logic}}); how to manipulate pseudo classes?

JavaScript can't get pseudo-class elements, but it can take a different approach. Pseudo-class style refers to the css variable, and then controls the css variable through js to achieve the effect of indirect manipulation of pseudo-class.

For example, this is a pseudo class:

.point-flicker:after {background-color: var (--afterBg);}

It relies on the afterBg variable.

If you need to modify its contents, you only need to use js to manipulate the contents of afterBg.

Point.value.style.setProperty ("--bg", colorConfig [props.type] .bg); changes in API how do components in Vue3 modify their own props?

There is an unusual situation in which the component needs to modify the Props that the parent component passes to itself.

For example, drawer components, mimic box components, and so on.

The common uses in vue2 are sync and v-model.

The only recommended way in vue3 is to use vMaiModelRank xxxx = "".

For example, the parent component passes:

Subcomponents:

... / /... Props: {visible: {type: Boolean,},}, changes in watch usage in Vue3

Watch has become much simpler.

Import {watch} from "vue"; watch (source, (currentValue, oldValue) = > {/ / logic})

Automatically executes the function passed in by the second parameter of watch when the source changes.

Changes in the usage of computed in Vue3

Computed has also become simpler.

Import {computed} from "vue" const v = computed (() = > {return x})

The variable returned by computed is a responsive object.

The skill of component Loop itself in Vue3

This is a technique for developing components.

Suppose you have tree-structured data with uncertain depth.

{"label": "root", "children": [{"label": "a", "children": [{"label": "A1", "children": []}, {"label": "a2" "children": []}

Its type definition is as follows:

Export interface Menu {id: string; label: string; children: Menu | null;}

You need to implement a tree component to render them. This technique is needed at this time.

{{menu.label}} import {defineComponent} from "vue"; export default defineComponent ({name: "Menu", props: {menu: {type: Object,})

The name of a component can be used directly in itself without the need to declare it in component.

Some pitfalls Vuex: be careful with Map

In Vuex, I designed a data structure for different states of storage modules (business concepts).

Type Code = number; export type ModuleState = Map

But I found a problem that when I modify a property in one of the value in Map, Vuex snooping is not triggered.

So I had to change the data structure to the form of an object.

Export type ModuleState = {[key in Code]: StateProperty}

Indexes in ts cannot use type aliases, but can be written as follows:

Type Code = number; export type ModuleState = {[key in Code]: StateProperty}

In addition, there is another problem with Map.

When a Proxy object of type Map is passed as a parameter, Map methods such as get, set, clear, and so on cannot be used, but TypeScript prompts them to be available. If you use these methods, you will get a Uncaught TypeError.

This problem does not occur if you use Object.

An exception occurs in WebSocket and cannot be listened to by try catch

Exceptions to ws can only be handled in onerror and onclose events, and try catch cannot catch them.

Sometimes, onerror and onclose execute successively, such as triggering onerror, causing the connection to close, followed by onclose.

Vue Devtools

Vue devtools currently does not support Vue3, but vue devtools is almost an essential tool in development, and the vue devtools beta version is currently available, but there are some Bug.

It is very easy to use, just restart the browser after installation. There is no need to set vue.config.devtools = true, and the devtools property does not exist for the vue.config instance in vue3.

ESbuild installation dependency

It is easy to encounter an error when installing dependencies while using vite to start the service.

Error: EBUSY: resource busy or locked, open'e:\ gxt\ property-relay-fed\ node_modules\ esbuild\ esbuild.exe'

The reason for this problem is that esbuild.exe, the compilation tool that vite depends on, is occupied. The solution is simply to stop vite, install the dependency and then restart vite.

The problem of debugging Vite in Chrome

There are some mobile pages in the system that need to be embedded in App.

There are two common ways to debug WebView. One simple way is to use Tencent's open source vcosnole, and another troublesome way to debug is to use Chrome's DevTools.

But vconsole is not as easy to use as you thought.

Image.png

So I chose to use Chrome debugging, chrome://inspect/#devices

But in the process of debugging, I found that the Chrome debugging tool is actually running TS source code, and the syntax of TS is directly regarded as a syntax error. (I started the development service using Vite. )

The solution is simple, but quite Low. Use vite build to compile the TS code into JS, and then use vite preview to start the service.

WebSocket

Websocket has nothing to do with Vue3, but I'll mention it briefly here.

The core concept of the device management system is the device, which has many properties and is also called data point in hardware. These properties are transmitted over a very long link to the user interface. The overall process is as follows: the hardware is uploaded to the access gateway through the tcp protocol, and then uploaded to the Internet of things platform through the mqtt protocol after processing by the access gateway. The Internet of things platform is then processed by the rule engine and sent to the business system in the form of webhook restful, and the business system is then pushed to the front end through websocket.

Although the data is presented to users over very long distances through layers of coding and decoding and different protocols, the front end only needs to care about websocket.

WebSocket reconnect

When doing reconnection, you need to pay attention to the problem of continuous execution of onerror and onclose, which is usually solved by using a similar anti-shake method.

My approach is to add a variable to control the number of reconnections.

Let connecting = false; / / after disconnecting, trigger onerror first, and then trigger onclose, which is mainly used to prevent repeated triggers

Conn (); function conn () {connecting = false; if (ctx.state.stateWS.instance & & ctx.state.stateWS.instance.close) {ctx.state.stateWS.instance.close ();} const url = ctx.state.stateWS.url + "Authorization=" + getAuthtication (); ctx.state.stateWS.instance = new WebSocket (url); ctx.state.stateWS.instance.onopen = () = > {ctx.commit (ActionType.SUCCESS);} Ctx.state.stateWS.instance.onclose = () = > {if (connecting) return; ctx.commit (ActionType.CLOSE); setTimeout () = > {conn ();}, 10 * 1000); connecting = true;}; ctx.state.stateWS.instance.onerror = () = > {if (connecting) return; ctx.commit (ActionType.ERROR); setTimeout () = > {conn () }, 10 * 1000); connecting = true;}; ctx.state.stateWS.instance.onmessage = function (this: WebSocket, ev: MessageEvent) {/ / logic} catch (e) {console.log ("e:", e);};} WebSocket connection activity log

The system is designed to run 24 hours a day. Therefore, websocket is easily disconnected by some network factors or other factors. Reconnection is a very important function, and it should also have the function of reconnection log.

In different environments of users, it is troublesome to check the connection status of WebSocket. Adding a connection log function is a good solution, so you can see the connection status at different times.

Image.png

It should be noted that these logs are stored in the user's browser memory, and the upper limit needs to be set to automatically clear the early logs.

WebSocket authentication

The authentication of websocket is a point that many people are easy to ignore.

In my system design, the authentication of restful API is realized by attaching the Authorization field to the request header and setting the generated JWT.

Websocket cannot set header, but you can set query to implement an authentication design similar to restful.

With regard to the expiration, renewal and permissions of ws authentication, you can keep it consistent with restful.

Script setup: a fresher API

Script setup is still an experimental feature, but it's really refreshing.

The general use of setup for a single-file component is as follows:

Import {defineComponent} from 'vue' export default defineComponent ({setup () {return {})

With script setup, the code looks like this:

The top-level variables and functions in the sciprt tag will be return out.

In this mode, a large amount of code is reduced, which can improve the development efficiency and reduce the mental burden.

But there are also several problems, such as how to use lifecycle and watch/computed functions in script setup? How to use components? How do I get props and context?

Working with components

After you import the component directly, vue automatically recognizes it, eliminating the need for component mount.

Import C from "component" uses lifecycle and listening calculation functions

It is basically no different from the standard writing method.

Import {watch, computed, onMounted} from "vue" uses props and context

Since setup is promoted to the script tag, it is naturally impossible to receive the parameters props and context.

So vue provides defineProps, defineEmit, useContext functions.

DefineProps

The usage of defineProps is almost the same as that of props in OptionsAPI.

Import {defineProps} from "vue"; interface Props {moduleID: string;} const props = defineProps (["moduleID"]); console.log (props.moduleID)

DefineEmit

The use of defineEmit is almost the same as the use of emit in OptionsAPI.

Import {defineEmit} from "vue"; const emit = defineEmit (["select"]); console.log (emit ("select"))

The first parameter of emit is the event name, followed by support for passing an indefinite number of parameters.

UseContext

UseContext is a hook function that returns a context object.

Const ctx = useContext () principle

The principle is quite simple. Added a layer of compilation process to compile script setup into standard mode code.

However, there are so many details in the implementation that the official version has not been released yet.

The modular development mode brought about by Vue3 Composition

The deepest feeling of this set of technology stack is the change in the way of development.

In the development of Vue2, Options API is very difficult to deal with pages with complex business logic. Tracking changes in a variable is a headache when the logic is thousands of lines long.

But with Composition API, this will no longer be a problem, it brings a new way of development, although there is a sense of React, but this is very good compared to before!

I use hooks to develop all the pages in this project.

In the device module, my js code looks like this.

Import {defineComponent, toRefs} from "vue"; import {useDeviceCreate} from ". / create"; import {useDeviceQuery} from ". / query"; import {useDeviceDelete} from ". / delete"; import {useUnbind} from ". / unbind"; import {useBind} from ". / bind"; import {useDeviceEdit} from ". / edit"; import {useState} from ". / state"; import {useAssign} from ". / from"; assign ({assign ()) {assign = assign () Const {query, devices} = queryObj; const reload = query Return {... toRefs (useDeviceCreate (reload)),... toRefs (queryObj),... toRefs (useDeviceDelete (reload)),... toRefs (useUnbind (reload)),... toRefs (useBind (reload)),... toRefs (useDeviceEdit (reload)),... toRefs (useState (devices)),... toRefs (useAssign ()),} },)

Each module does its own job and has its own internal data. If each module needs to share data, it can be passed through Vuex or in the setup of the top-level component, such as the reload function above.

My directory structure is like this.

This is the end of the introduction to "how to use TypeScript in Vue3". Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.

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