vue3组件TS类型声明实例代码

简介: vue3组件TS类型声明实例代码

为 props 标注类型

当使用

<script setup lang="ts">
 
const props = defineProps({
 
  foo: { type: String, required: true },
 
  bar: Number
 
})
 
props.foo // string
 
props.bar // number | undefined
 
</script>

这被称为 运行时声明 ,因为传递给 defineProps() 的参数会作为运行时的 props 选项使用。

第二种方式,通过泛型参数来定义 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 默认值的能力。我们可以通过目前实验性的 响应性语法糖 来解决:

<script setup lang="ts">
 
interface Props {
 
  foo: string
 
  bar?: number
 
}
 
// 响应性语法糖 默认值会被编译为等价的运行时选项
 
const { foo, bar = 100 } = defineProps()

这个行为目前需要在配置中显式地选择开启:

// vite.config.js
 
export default {
 
  plugins: [
 
    vue({
 
      reactivityTransform: true
 
    })
 
  ]
 
}
 
// vue.config.js
 
module.exports = {
 
  chainWebpack: (config) => {
 
    config.module
 
      .rule('vue')
 
      .use('vue-loader')
 
      .tap((options) => {
 
        return {
 
          ...options,
 
          reactivityTransform: true
 
        }
 
      })
 
  }
 
}

如果没有使用

import { defineComponent } from 'vue'
 
export default defineComponent({
 
  props: {
 
    message: String
 
  },
 
  setup(props) {
 
    props.message // <-- 类型:string
 
  }


相关文章
|
3天前
|
JavaScript 前端开发 CDN
vue3速览
vue3速览
12 0
|
3天前
|
设计模式 JavaScript 前端开发
Vue3报错Property “xxx“ was accessed during render but is not defined on instance
Vue3报错Property “xxx“ was accessed during render but is not defined on instance
|
3天前
|
JavaScript API
Vue3 官方文档速通(中)
Vue3 官方文档速通(中)
18 0
|
3天前
|
缓存 JavaScript 前端开发
Vue3 官方文档速通(上)
Vue3 官方文档速通(上)
20 0
|
3天前
Vue3+Vite+Pinia+Naive后台管理系统搭建之五:Pinia 状态管理
Vue3+Vite+Pinia+Naive后台管理系统搭建之五:Pinia 状态管理
8 1
|
3天前
Vue3+Vite+Pinia+Naive后台管理系统搭建之三:vue-router 的安装和使用
Vue3+Vite+Pinia+Naive后台管理系统搭建之三:vue-router 的安装和使用
7 0
|
3天前
Vue3+Vite+Pinia+Naive后台管理系统搭建之二:scss 的安装和使用
Vue3+Vite+Pinia+Naive后台管理系统搭建之二:scss 的安装和使用
6 0
|
3天前
|
JavaScript 前端开发 API
Vue3 系列:从0开始学习vue3.0
Vue3 系列:从0开始学习vue3.0
9 1
|
3天前
|
网络架构
Vue3 系列:vue-router
Vue3 系列:vue-router
8 2
|
3天前
Vue3+Vite+Pinia+Naive后台管理系统搭建之一:基础项目构建
Vue3+Vite+Pinia+Naive后台管理系统搭建之一:基础项目构建
7 1