//当使用 <script setup> 时,defineProps() 宏函数支持从它的参数中推导类型
<script setup lang="ts">
//第一种 通过泛型参数定义 这种方法更直接
const props = defineProps<{
msg:string,
age:number | string
}>()
//第二种 required为必传
const props = defineProps({
msg: { type: String },
age:{type:Number , required:true}
})
//第三种 withDefaults默认参数
interface Props {
msg?: string
age?: Number | string
}
const {msg,age } = withDefaults(defineProps<Props>(), {
msg: 'hello',
age: () => '30'
})
console.log(props);
</script>
// emits 标注类型
//使用 <script setup>
<script setup lang="ts">
//运行时
const emit = defineEmits(['change'])
//基于类型 (void 特殊函数类型 表示此函数没有返回值)
const emit = defineEmits<{
(e: 'change', id: number): void
}>()
//事件触发
function btn() {
emit('change',10)
}
</script>
//非setup
import { defineComponent } from 'vue'
export default defineComponent({
emits: ['change'],
setup(props, { emit }) {
emit('change') // 类型检查 / 自动补全
}
})
//为 ref() 标注类型 ref 会根据初始化时的值自动推导其类型
import { ref } from 'vue'
// 推导出的类型:Ref<number>
const year = ref(2020)
year.value = '2020'
<script setup lang="ts">
//第一种通过接口指定类型
import { ref } from 'vue'
import type { Ref } from 'vue'
const year: Ref<string | number> = ref('2020')
year.value = 2020 // 成功!
//第二种通过泛型指定类型
const age = ref<string | number>(20)
age.value = 20 // 成功!
</script>
//reactive() 标注类型
<script setup lang="ts">
// reactive() 也会隐式地从它的参数中推导类型:
import { reactive } from 'vue'
// 推导得到的类型:{ title: string }
const book = reactive({ title: '值' })
//通过接口指定类型
interface user {
name: string,
age?:number
}
const root:user = reactive({
name: '某某某',
age:10
})
</script>
//为 computed() 标注类型
//computed() 会自动从其计算函数的返回值上推导出类型:
<script setup lang="ts">
import { ref, computed } from 'vue'
const count = ref(0)
// 推导得到的类型:ComputedRef<number>
const double = computed(() => count.value * 2)
const result = double.value.split('')
//通过泛型指定类型
const double = computed<number>(() => {
// 若返回值不是 number 类型则会报错
return 1
})
</script>
//为 dom 模板引用标注类型
<script setup lang="ts">
import { ref, onMounted } from 'vue'
const el = ref<HTMLInputElement | null>(null)
onMounted(() => {
el.value?.focus()
})
</script>
<template>
<input ref="el" />
</template>
//为组件模板引用标注类型
//有时,我们需要为一个子组件添加一个模板 ref,以便调用它公开的方法。比如,我们有一个 MyModal 子组件,它有一个打开模态框的方法:
<!-- MyModal.vue -->
<script setup lang="ts">
import { ref } from 'vue'
const isContentShown = ref(false)
const open = () => (isContentShown.value = true)
defineExpose({
open
})
</script>
<!-- App.vue -->
<script setup>
import MyModal from './MyModal.vue'
const modal = ref<InstanceType<typeof MyModal> | null>(null)
const openModal = () => {
modal.value?.open()
}
</script>
vue3 props ,emits,ref,reactive,computed,dom模版,组件模板ts类型定义
最新推荐文章于 2024-08-30 17:37:19 发布
文章详细介绍了Vue3的<scriptsetup>标签如何配合TypeScript实现组件属性的类型安全定义,包括defineProps、defineEmits、ref、reactive和computed的类型标注,以及如何为模板引用和子组件交互进行类型注解。
摘要由CSDN通过智能技术生成