Vue3 + TS 的基本使用及遇到的问题

182 阅读1分钟

vue3新增了composition api的写法,更接近react的写法

setup 语法糖

一个组件选项,在组件被创建之前props 被解析之后执行。它是组合式 API 的入口。 <script setup> 是在单文件组件 (SFC) 中使用组合式 API 的编译时语法糖。相比于普通的 <script> 语法,它具有更多优势:

  • 更少的样板内容,更简洁的代码。

  • 能够使用纯 Typescript 声明 props 和抛出事件。

  • 更好的运行时性能 (其模板会被编译成与其同一作用域的渲染函数,没有任何的中间代理)。

  • 更好的 IDE 类型推断性能 (减少语言服务器从代码中抽离类型的工作)。 使用这个语法,需要将 setup attribute 添加到 <script> 代码块上:

<script setup lang="ts"> </script>

响应式 ref

import { ref } from "vue";
let str = ref<string>("test");

还可以指定复杂类型

const foo = ref<string | number>('foo') // foo 的类型Ref<string | number>
foo.value = 123 // ok!

props/emit

  • 仅限类型的 props/emit 声明
defineProps<{ title: string }>();
const emit = defineEmits<{ 
    (e: 'change', id: number): void 
    (e: 'update', value: string): void 
}>()

遇到的问题

做好所有配置后,主要遇到以下两个问题

vite 打包报错/告警

"@charset" must be the first rule in the file }@charset "UTF-8";

image.png

原因:使用了scss类库 sass,scss编译的时候,因为被编译的文件里可能有中文导致

解决:在vite.config.js里面,加一个sass的配置,把charset关掉就行了 官网对css预处理的api vite.config.js 中的配置:

export default defineConfig({
  css: {
    preprocessorOptions: {
      scss: {
        charset: false
      }
    }
  }
})

去除 Typescript 全局变量的 eslint 报错

1. 使用 var 定义全局变量

var 相关声明下会带下划线,并报错

Unexpected var, use let or const instead.

解决:在 .eslintrc 配置文件中增加规则

rules: {
    // 全局变量允许使用 var
    'no-var': 'off',
}

2. 使用 global 定义全局变量

global 相关声明下会带下划线,并报错

Augmentations for the global scope can only be directly nested

in external modules or ambient module declarations.

解决:在 global.d.ts 声明文件中添加一行代码

export {}