<script setup> 相关宏函数学习

343 阅读2分钟

🦄 defineProps

js 形式:运行时声明


const props = defineProps({
	modelValue: {
		type: String,
		default: '1'
	}
})

ts 形式 <> 类型声明

const props = defineProps<{
	modelValue: string
}>()

将类型单独 抽离

interface Props {
	modelValue: string
}
const props = defineProps<Props>()

默认值: withDefaults

interface Props {
	modelValue: string
}
const props = withDefaults(defineProps<Props>(), {
	modelValue: '1'
})

🦄 defineEmits

js形式 运行时声明

const emit = defineEmits(['change'])

ts形式 <>类型声明

const emit = defineEmits<{
	change: [id: number]
}>()

目前此方式还没有提供函数返回值类型,可以使用下面方式

const emit = defineEmits<{
	(e: 'change', value: string): void
}>()

🦄 defineModel 与 update:modelValue

先来看一个之前如何写一个 v-model

  • 子组件 通过 props 接收数据 + emit('update:modelValue', e.target.value) 更改数据

父组件

<base-input v-model="inputValue" label="value" ref="baseInputRef" /> {{ inputValue }}

子组件

<template>
	<input :value="props.modelValue" placeholder="输入框" @input="(e) => emit('update:modelValue', e.target.value)" />
</template>

<script setup lang="ts">
interface Props {
	modelValue: string
}
const props = withDefaults(defineProps<Props>(), {
	modelValue: '1'
})

defineModel

不再使用props接收和 emit('update:modelValue',e.target.value) ,直接使用 defineModel 就实现了v-model

<template>
	<input v-model="val" placeholder="输入框" />
</template>

<script setup lang="ts">
const val = defineModel<string>()
<script/>

🦄 带参数的v-model

我们只有一个需要双向绑定,用默认 modelValue 即可,如果我们需要多个双向绑定,需要带参数的v-model

父组件

<base-input v-model:name="name" label="value" ref="baseInputRef" /> {{ name }}

子组件

//3.4 前
<input :value="name" placeholder="输入框" @input="(e) => emit('update:name', e.target.value)" />
defineProps(['name'])
//3.4 用法
<input v-model="name" />
const name = defineModel<string>('name', {
	type: String, default: '1'
})

🦄 defineExpose

使用 <script setup> 的组件是默认关闭的: 即通过模板引用或者 $parent 链获取到的组件的公开实例,不会暴露任何在 <script setup> 中声明的绑定.可以通过 defineExpose 向外暴露属性/方法


<script setup>
const msg = ref('setupScript')
const count = ref(0)
const increase = () => {
	count.value++
}
defineExpose({ msg, count, increase })
</script>

在父子组件传值,这个很管用,可以参考juejin.cn/post/734057…

🦄 defineOptions

之前我们为组件命名需要再写一个script 标签,或者 使用setup 函数,比较麻烦。现在直接使用 defineOptions可以为其添加组件名字(个人感觉这就像一个补丁,由于使用了script setup 出现的问题,而新增加的defineOptions 来做补丁...)

defineOptions({
    name: 'tree'
})