要将 props 与<script setup>
一起使用,您需要使用组件 prop 选项作为参数调用defineProps()
,这将定义组件实例上的 props 并返回一个带有 props 的reactive
对象,您可以按如下方式使用:
<template>
<TopNavbar title="room" />
<div>
{{ no }}
</div>
</template>
<script setup>
import TopNavbar from "@/layout/TopNavbar.vue";
import { defineProps, reactive } from "vue";
const props = defineProps({
no: String,
});
const { no } = toRefs(props);
const state = reactive({
room: {},
});
const init = async () => {
const { data } = await getRoomByNo(no.value);
console.log(data);
};
init();
</script>
如果您使用的是打字稿,另一种方法是传递仅类型声明并从中推断道具类型。 优点是您将获得更严格的类型安全性
,但您不能拥有默认值。
<template>
<TopNavbar title="room" />
<div>
{{ no }}
</div>
</template>
<script setup>
import TopNavbar from "@/layout/TopNavbar.vue";
import { defineProps, reactive } from "vue";
const props = defineProps<{
no: string,
}>();
const { no } = toRefs(props);
const state = reactive({
room: {},
});
const init = async () => {
const { data } = await getRoomByNo(no.value);
console.log(data);
};
init();
</script>
编辑
现在可以使用仅类型道具的默认值:
interface Props {
msg?: string
}
const props = withDefaults(defineProps<Props>(), {
msg: 'hello'
})