像标题,
关于链接:
New script setup
(without ref sugar)
<template>
<TopNavbar title="room" />
<div>
{{ no }}
</div>
</template>
<script setup>
import TopNavbar from '@/layout/TopNavbar.vue'
import { defineProps, reactive } from 'vue'
defineProps({
no: String
})
const state = reactive({
room: {}
})
const init = async () => {
// I want use props in this
// const { data } = await getRoomByNo(props.no)
// console.log(data);
}
init()
</script>
<style>
</style>
最佳答案
使用 <script setup>
的 Prop 您需要调用defineProps()
以组件 prop 选项作为参数,它定义组件实例上的 props 并返回 reactive
带有 Prop 的对象,您可以按如下方式使用:
<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>
如果您使用的是 typescript ,另一种方法是传递仅类型声明并从中推断 Prop 类型。优点是您将获得更严格的类型安全性,但您不能拥有默认值。<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>
编辑现在可以使用仅类型 Prop 的默认值:
interface Props {
msg?: string
}
const props = withDefaults(defineProps<Props>(), {
msg: 'hello'
})
关于javascript - 如何在 vue3 的 <script setup> 中使用 props,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66382293/