# 笔记

# 2022 年 6 月 1 日

# TypeScript Vue Plugin

当使用 ts+vue3 组合式 API 开发项目时,如若遇到如下异常:Cannot find module '../views/***.vue' or its corresponding type declarations.

安装 TypeScript Vue Plugin (opens new window) 插件即可消除异常,另外需要将 vue2 版本的 Vetur 禁用

# 2022 年 6 月 2 日

# Props 解构默认值

当使用基于类型的声明时,可能无法直接为 props 声明默认值,但可以通过 withDefaults 编译器宏来解决,相当于 propsdefault 选项:

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

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

withDefaults 帮助程序为默认值提供类型检查,并确保返回的 props 类型删除了已声明默认值的属性的可选标志。

或者可以显式地启用 (opens new window)实验性的响应式语法糖 (opens new window)

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

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

# 2022 年 6 月 3 日

# defineEmits 提示 “xx is defined but never used”

<setup ts> 模式下定义 emitseslint 会报异常,如下所示:

const emits = defineEmits<{
  (e: "handleChange", value: string): void // 'e' is defined but never used
}>()

即便是直接 copy 官方文档上的代码也是会提异常,因此需要去调整一下 eslint 配置。配置的时候需要注意,避免直接把 "no-unused-vars" 给屏蔽掉,这样的话所有相关的检测都被禁用了,这显然不是我们想要的。

那么就考虑排除特定前缀的参数了,如下所示:

rules: {
    "no-unused-vars": [
      "error",
      {
        vars: "all",
        args: "after-used",
        ignoreRestSiblings: true,
        argsIgnorePattern: "^_",
      },
    ],
  },

这样的话,我们只需要使用 _ 前缀即可忽略 eslint 检查

# 2022 年 6 月 4 日

# ref() 标注类型

ref 标注类型的多种方式:

const str = ref(2020)
const str: Ref<string | number> = ref(2020)
const str = ref<string | undefined>(2020)
const n = ref<number>() // 结果是 number 和 undefined
Last Updated: 11/17/2022, 4:39:57 PM