Home  >  Article  >  Web Front-end  >  How to use TypeScript in Vue3

How to use TypeScript in Vue3

WBOY
WBOYforward
2023-05-18 20:52:041315browse

How to declare a type whose field name is an enumeration?

According to design, the type field should be an enumeration value and should not be set arbitrarily by the caller.

The following is the enumeration declaration of Type, with a total of 6 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 with undefined key types.

Use type to declare:

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

Using interface can only be like this:

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

Because the index of interface can only be the basic type, neither can type aliases. The index of type can be a composite type.

Vue 3 How to get element instance?

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

The new usage is:

Add the 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 with the same name in the return object of setup.

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

Step one:

<div></div>

Step two:

const point = ref<htmldivelement>(null);</htmldivelement>

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

The third step:

return { point };

This step is essential. If the returned object does not contain this property with the same name, the ref object accessed in onMounted will be null.

Step 4:

onMounted(() => {    if (point?.value) {      // logic    }  });

How to operate pseudo-classes?

JavaScript cannot get pseudo-class elements, but you can think of it differently. The pseudo-class style refers to css variables, and then controls the css variables through js to complete the effect of indirectly operating the pseudo-class.

For example, this is a pseudo class:

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

It depends on the afterBg variable.

If you need to modify its content, you only need to use js to operate the content of afterBg.

point.value.style.setProperty("--bg", colorConfig[props.type].bg);

API changes

How do components in Vue3 modify their own props?

There is a not very common situation where a component needs to modify the Props passed to itself by the parent component.

For example, drawer components, mimic box components, etc.

Common usage in vue2 is sync and v-model.

Only v-model:xxx="" is recommended in vue3.

For example, the parent component passes:

<ws-log></ws-log>

Child component:

<template>      <div>      ...     </div>  </template>  <script>  // ...   props: {      visible: {        type: Boolean,      },    },  </script>

Changes in watch usage in Vue3

watch becomes simpler.

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

When the source changes, the function passed in the second parameter of watch is automatically executed.

Changes in computed usage in Vue3

computed has also become simpler.

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

computed The returned variable is a reactive object.

The technique of component looping itself in Vue3

This is a technique for developing components.

Suppose you have a tree-structured data of uncertain depth.

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

Its type is defined as follows:

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

You need to implement a tree component to render them. This is where this technique comes in handy.

<template>      <div>{{ menu.label }}</div>      <menu></menu>  </template>  <script>  import { defineComponent } from "vue";  export default defineComponent({    name: "Menu",    props: {      menu: {        type: Object,      },    },  });  </script>

The name of the component can be used directly in itself without being declared in component.

Some pitfalls

Vuex: Use Map with caution

In Vuex, I designed a data structure to store different states of the module (business concept).

type Code = number;  export type ModuleState = Map<code>;</code>

But I found a problem. When I modify an attribute in a value in the Map, Vuex's monitoring will not be triggered.

So I had to modify the data structure into the form of an object. Type aliases cannot be used for indexes in

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

ts, but they can be written as follows:

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

In addition, Map also has another problem.

When a Proxy object of Map type is passed as a parameter, Map methods such as get, set, clear, etc. cannot be used, but TypeScript will prompt that these methods are available. If you use these methods, you will get an Uncaught TypeError.

If you use Object, this problem will not occur.

WebSocket exceptions cannot be monitored by try catch

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

Sometimes, onerror and onclose will be executed continuously. For example, if onerror is triggered, causing the connection to be closed, onclose will be triggered immediately.

Vue Devtools

vue devtools currently cannot support Vue3, but vue devtools is almost an indispensable tool in development. The vue devtools beta version can currently be used, but there are some bugs.

Usage is very simple, just restart the browser after installation. There is no need to set vue.config.devtools = true, the devtools attribute does not exist in the vue.config instance in vue3.

ESbuild installation dependencies

It is very 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 the compilation tool esbuild.exe that vite depends on is occupied. The solution is very simple, which is to stop vite, install the dependencies, and then restart vite.

Problems with Vite debugging in Chrome

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

常见的调试 WebView 的方法有两种,一种简单的方式是使用腾讯开源的 vcosnole,另一种麻烦一些的调试方式是使用 Chrome 的 DevTools。

但是 vconsole 并没有想象中那么好用。

How to use TypeScript in Vue3

image.png

所以我选择使用 Chrome 调试,chrome://inspect/#devices

但是在调试过程中我发现 Chrome 调试工具里面竟然运行的是 TS 源码,TS 的语法直接被认为语法错误。(我是使用 Vite 启动的开发服务。)

解决方案很简单,但挺 Low。先使用 vite build 把 TS 代码编译成 JS,再使用 vite preview 启动服务。

WebSocket

websocket 和 Vue3 没什么关系,但是在这里简单提一下。

设备管理系统的核心概念是设备,设备会有很多属性,在硬件上也被称作数据点。这些属性会经历非常长的链路传输到用户界面上。整体流程大概是:硬件通过 tcp 协议上传到接入网关,接入网关处理后再通过 mqtt 协议上传到物联网平台,物联网平台再经过规则引擎处理,通过 webhook restful 的形式发送到业务系统,业务系统再通过 websocket 推送到前端。

虽然数据通过层层编解码、不同的协议绕了非常远的距离呈现到用户面前,但是前端只需要关心 websocket 就足够了。

WebSocket 重连

在做重连时,需要注意 onerror 和 onclose 连续执行的问题,通常是使用类似防抖的方法来解决。

我的做法是增加一个变量来控制重连次数。

let connecting = false; // 断开连接后,先触发 onerror,再触发 onclose,主要用于防止重复触发

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 连接活动日志

系统是设计成 7*24 小时不间断运行。所以 websocket 很容易受到一些网络因素或者其它因素的影响发生断开,重连是一项非常重要的功能,同时还应该具备重连日志功能。

在用户的不同环境中,排查 WebSocket 的连接状态很麻烦,添加一个连接日志功能是比较不错的方案,这样可以很好的看到不同时间的连接情况。

How to use TypeScript in Vue3

image.png

需要注意,这些日志是存储在用户的浏览器内存中的,需要设置上限,到达上限要自动清除早期日志。

WebSocket 鉴权

websocket 的鉴权是很多人容易忽视的一个点。

我在系统设计中,restful API 的鉴权是通过在 request header 上附带 Authorization 字段,设置生成的 JWT 来实现的。

websocket 无法设置 header,但是可以设置 query,实现思路类似 restful 的认证设计。

关于 ws 鉴权的过期、续期、权限等问题,和 restful 保持一致即可。

script setup:更加清爽的 API

script setup 至今仍是一个实验性特性,但它确实非常清爽。

单文件组件的 setup 常规用法像下面这样:

<script> import { defineComponent } from &#39;vue&#39;  export default defineComponent({   setup () {      return {}    }  })  </script>

使用 script setup 后,代码变成了下面这样:

<script>    </script>

在 sciprt 标签中的顶层变量、函数都会 return 出去。

在这种模式下,减少了大量代码,可以提高开发效率、降低心智负担。

但这时也存在几个问题,比如在 script setup 中怎么使用生命周期和 watch/computed 函数?怎么使用组件?怎么获取 props 和 context?

使用组件

直接导入组件后,vue 会自动识别,无需使用 component 挂载。

<script>    import C from "component"  </script>

使用生命周期和监听计算函数

和标准写法基本无差异。

<script>    import { watch, computed, onMounted } from "vue"  </script>

使用 props 和 context

由于 setup 被提升到 script 标签上了,自然也就没办法接收 props 和 context 这两个参数。

所以 vue 提供了 defineProps、defineEmit、useContext 函数。

defineProps

defineProps 的用法和 OptionsAPI 中的 props 用法几乎一致。

<script>  import { defineProps } from "vue";  interface Props {    moduleID: string;  }  const props = defineProps<Props>(["moduleID"]);  console.log(props.moduleID);  </script>

defineEmit

defineEmit 的用法和 OptionsAPI 中的 emit 用法也几乎一致。

<script>  import { defineEmit } from "vue";  const emit = defineEmit(["select"]);  console.log(emit("select"));  </script>

emit 的第一个参数是事件名称,后面支持传递不定个数的参数。

useContext

useContext 是一个 hook 函数,返回 context 对象。

const ctx = useContext()

原理

原理相当简单。增加了一层编译过程,将 script setup 编译成标准模式的代码。

但是实现上有非常多的细节,所以导致至今仍未推出正式版。

Vue3 Composition 所带来的模块化开发方式

这套技术栈带给我最深的感受还是开发方式上的变化。

在 Vue2 的开发中,Options API 在面对业务逻辑复杂的页面时非常吃力。当逻辑长达千行时,追踪一个变量的变化是一件非常头痛的事情。

但是有了 Composition API 后,这将不再是问题,它带来了一种全新的开发方式,虽然有种 React 的感觉,但这相比之前已经非常棒了!

这项目中所有的页面,我都使用 hooks 的方式开发。

在设备模块中,我的 js 代码是这样的。

<script>  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 "./assign";  export default defineComponent({    setup() {      const queryObj = useDeviceQuery();      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()),      };    },  });  </script>

每个模块各司其职,各自有自己的内部数据,各个模块如果需要共享数据,可以通过 Vuex,或者在顶层组件的 setup 中传递,比如上面的 reload 函数。

我的目录结构是这样的。

How to use TypeScript in Vue3

The above is the detailed content of How to use TypeScript in Vue3. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete