首页 > 其他分享 >vue3+ts基础使用

vue3+ts基础使用

时间:2023-02-07 17:57:19浏览次数:53  
标签:vue const string 基础 ts vue3 类型 ref 标注

详见: vue 官方文档

响应式数据

<script setup lang="ts">
import { ref, reactive, computed } from "vue";
import type { Ref } from "vue";

// ref
// 可通过 Ref 或 调用ref时传入一个泛型参数
type code = number | string;
let ts_ref1 = ref<string>("字符类型");
let ts_ref2: Ref<number[]> = ref([1, 2]);
let ts_ref3 = ref<code>(1);
ts_ref3.value = "1";

// reactive
// 显性的给变量进行标注
interface student {
  name: string;
  age?: number;
  [orders: string]: any;
}
const ts_reactive: student = reactive({
  id: 1,
  name: "小明",
  age: 12,
});

// computed
// 调用computed时传入一个泛型参数
let data = ref<number>(1);
const ts_computed = computed<number>(() => data.value * 10);
</script>

模板引用标注(获取 dom)

<template>
  <div class="dataDefinition">
    <div class="moduel">
      <h3 ref="title">function-ts:事件标注和dom获取:</h3>
      <button @click="handleClick">打印event和标题dom</button>
    </div>
  </div>
</template>

<script setup lang="ts">
// 获取dom
const title = ref<HTMLElement | null>();
const handleClick = (event: Event): void => {
  console.log("event=>", event);
  console.log("dom=>", title.value);
};
</script>

props 标注类型

<script setup lang="ts">
const props = defineProps<{
  foo: string;
  bar?: number;
}>();
</script>

也可以将 props 的类型移入一个单独的接口中:

<script setup lang="ts">
interface Props {
  foo: string;
  bar?: number;
}

const props = defineProps<Props>();
</script>

Props 解构默认值

当使用基于类型的声明时,我们失去了为 props 声明默认值的能力。这可以通过 withDefaults 编译器宏解决:

export interface Props {
  msg?: string;
  labels?: string[];
}

const props = withDefaults(defineProps<Props>(), {
  msg: "hello",
  labels: () => ["one", "two"],
});

可以使用目前为实验性的响应性语法糖:

<script setup lang="ts">
interface Props {
  name: string;
  count?: number;
}

// 对 defineProps() 的响应性解构
// 默认值会被编译为等价的运行时选项
const { name, count = 100 } = defineProps<Props>();
</script>

这个行为目前需要显式地 选择开启

emits 标注类型

<script setup lang="ts">
// 运行时
const emit = defineEmits(["change", "update"]);

// 基于类型
const emit = defineEmits<{
  (e: "change", id: number): void;
  (e: "update", value: string): void;
}>();
</script>

ref() 标注类型

ref 会根据初始化时的值推导其类型:

import { ref } from "vue";

// 推导出的类型:Ref<number>
const year = ref(2020);

// => TS Error: Type 'string' is not assignable to type 'number'.
year.value = "2020";

调用 ref() 时传入一个泛型参数,来覆盖默认的推导行为:

// 得到的类型:Ref<string | number>
const year = ref<string | number>("2020");

year.value = 2020; // 成功!

你指定了一个泛型参数但没有给出初始值,那么最后得到的就将是一个包含 undefined 的联合类型:

// 推导得到的类型:Ref<number | undefined>
const n = ref<number>();

reactive() 标注类型

reactive() 也会隐式地从它的参数中推导类型:

import { reactive } from "vue";

// 推导得到的类型:{ title: string }
const book = reactive({ title: "Vue 3 指引" });

要显式地标注一个 reactive 变量的类型,我们可以使用接口:

import { reactive } from "vue";

interface Book {
  title: string;
  year?: number;
}

const book: Book = reactive({ title: "Vue 3 指引" });

:::tip
不推荐使用 reactive() 的泛型参数,因为处理了深层次 ref 解包的返回值与泛型参数的类型不同。
:::

computed() 标注类型

computed() 会自动从其计算函数的返回值上推导出类型:

import { ref, computed } from "vue";

const count = ref(0);

// 推导得到的类型:ComputedRef<number>
const double = computed(() => count.value * 2);

// => TS Error: Property 'split' does not exist on type 'number'
const result = double.value.split("");

还可以通过泛型参数显式指定类型:

const double = computed<number>(() => {
  // 若返回值不是 number 类型则会报错
});

事件处理函数标注类型

在处理原生 DOM 事件时,应该为我们传递给事件处理函数的参数正确地标注类型。让我们看一下这个例子:

<script setup lang="ts">
function handleChange(event) {
  // `event` 隐式地标注为 `any` 类型
  console.log(event.target.value)
}
</script>

<template>
  <input type="text" @change="handleChange" />
</template>

没有类型标注时,这个 event参数会隐式地标注为 any 类型。这也会在 tsconfig.json 中配置了 "strict": true"noImplicitAny": true 时报出一个 TS 错误。因此,建议显式地为事件处理函数的参数标注类型。此外,你可能需要显式地强制转换 event 上的属性:

function handleChange(event: Event) {
  console.log((event.target as HTMLInputElement).value)
}

provide / inject 标注类型

provideinject 通常会在不同的组件中运行。要正确地为注入的值标记类型,Vue 提供了一个 InjectionKey 接口,它是一个继承自 Symbol 的泛型类型,可以用来在提供者和消费者之间同步注入值的类型:

import { provide, inject } from "vue";
import type { InjectionKey } from "vue";

const key = Symbol() as InjectionKey<string>;

provide(key, "foo"); // 若提供的是非字符串值会导致错误

const foo = inject(key); // foo 的类型:string | undefined

建议将注入 key 的类型放在一个单独的文件中,这样它就可以被多个组件导入。

当使用字符串注入 key 时,注入值的类型是 unknown,需要通过泛型参数显式声明:

const foo = inject<string>("foo", "bar"); // 类型:string

如果你确定该值将始终被提供,则还可以强制转换该值:

const foo = inject("foo") as string;

模板引用标注类型

模板引用需要通过一个显式指定的泛型参数和一个初始值 null 来创建:

<script setup lang="ts">
import { ref, onMounted } from 'vue'

const input = ref<HTMLInputElement | null>(null)

onMounted(() => {
  input.value?.focus()
})
</script>

<template>
  <input ref="input" />
</template>

注意为了严格的类型安全,有必要在访问 el.value 时使用可选链或类型守卫。这是因为直到组件被挂载前,这个 ref 的值都是初始的 null,并且在由于 v-if 的行为将引用的元素卸载时也可以被设置为 null

组件模板引用标注类型

为了获取 MyModal 的类型,我们首先需要通过 typeof 得到其类型,再使用 TypeScript 内置的 InstanceType 工具类型来获取其实例类型:

<!-- App.vue -->
<script setup lang="ts">
import MyModal from './MyModal.vue'

const modal = ref<InstanceType<typeof MyModal> | null>(null)

const openModal = () => {
  modal.value?.open()
}
</script>

PropType <T>

用于在用运行时 props 声明时给一个 prop 标注更复杂的类型定义。

对象

import { PropType } from 'vue'

interface Book {
  title: string
  author: string
  year: number
}

export default {
  props: {
    book: {
      // 提供一个比 `Object` 更具体的类型
      type: Object as PropType<Book>,
      required: true
    }
  }
}

数组

import {defineComponent, PropType} from 'vue'
export interface ColumnProps{
    id: string;
    title: string;
    avatar: string;
    description: string;
}
export default defineComponent({
    name:'ColumnList',
    props:{
        list:{
            type:Array as PropType<ColumnProps[]>,
            required:true
        }
    }
})

标签:vue,const,string,基础,ts,vue3,类型,ref,标注
From: https://www.cnblogs.com/icey-Tang/p/17099324.html

相关文章

  • How to set the sprint goal before each quarter and pull the tickets into the cur
    ①IfoundtheepicIwanttodoandcreatedtheticketstodo  ②ThenIfoundmyticketinthebacklog  ③Rightclickandselec......
  • vue3新增特性合集
    封装公共方法到原型上再vue2中全局挂载方法使用的是Vue.prototype.xxx的形式来挂载的,但是在vue3中这个方法将不能使用,取而代之的是app.config.globalProperties......
  • Linux基础第一章:基础知识与基础命令
    一、虚拟机网络环境-网卡三种连接方式桥接模式:虚拟机和本机使用同一个物理网卡,共享主机IP地址nat模式:内外网地址转换,生成一个VMware8网卡,此网卡必须与虚拟机在同一个网段,......
  • 物联网勒索软件攻击或成为关键基础设施安全保护的噩梦
    勒索软件攻击仍然是关键基础设施部门和运营技术(OT)环境的噩梦。近日,一种称为物联网勒索软件或R4IoT方法的新攻击浮出水面。概念验证(PoC)揭示了网络犯罪分子日益复杂的......
  • GStreamer基础教程13 - 调试Pipeline
    摘要在很多情况下,我们需要对GStreamer创建的Pipeline进行调试,来了解其运行机制以解决所遇到的问题。为此,GStreamer提供了相应的调试机制,方便我们快速定位问题。 查......
  • 2023牛客寒假算法基础集训营5 A-L
    比赛链接A题解知识点:前缀和,二分。找到小于等于\(x\)的最后一个物品,往前取\(k\)个即可,用前缀和查询。时间复杂度\(O(n+q\logn)\)空间复杂度\(O(n)\)代码#i......
  • UVA12096 The SetStack Computer 栈的应用 好题
    题意翻译对于一个以集合为元素的栈,初始时栈为空。输入的命令有如下几种:PUSH:将空集{}压栈DUP:将栈顶元素复制一份压入栈中UNION:先进行两次弹栈,将获得的集合A和B取并集,将结......
  • Qt::WA_TransparentForMouseEvents
    (一)Qt::WA_TransparentForMouseEvents实现鼠标穿透功能,类似“隔空取物、隔山打牛”的效果。//qwidget.hvoidsetAttribute(Qt::WidgetAttribute,boolon=true);启......
  • GStreamer基础教程01 - Hello World
    摘要在面对一个新的软件库时,第一步通常实现一个“helloworld”程序,来了解库的用法。对于GStreamer,我们可以实现一个极简的播放器,来了解GStreamer的使用。 环境配置为......
  • GStreamer基础教程02 - 基本概念
    摘要在 Gstreamer基础教程01-HelloWorld中,我们介绍了如何快速的通过一个字符串创建一个简单的pipeline。为了能够更好的控制pipline中的element,我们需要单独创建eleme......