How to use props in <script setup> in vue3
To use props with <script setup>
you need to call defineProps()
with the component prop options as the argument, this defines the props on the component instance and returns a reactive
object with the props which you can use as follows:
<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>
If you are using typescript the alternative way to do this is pass a type only declaration and infer the prop types from that. Pro's are that you'll get stricter type safety but you cannot have default values.
<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>
EDIT
Defaults with type only props are now possible:
interface Props { msg?: string}const props = withDefaults(defineProps<Props>(), { msg: 'hello'})
As per the ongoing RFC, the setup
tag can have a string following where you can define which context you wish to have, like so:
<script setup="props, { emit }">import { watchEffect } from 'vue';watchEffect(() => console.log(props.msg));emit('foo');</script>
These are the same arguments that the setup()
method receives.
I read "Newscript setup
" and found the answer
first,use variable save defineProps
const props = defineProps({ no: String})
then use it
const init = async () => { console.log(props.no);}
this is all code:
<template> <TopNavbar title="room" /> <div> {{ no }} </div></template><script setup>import TopNavbar from '@/layout/TopNavbar.vue'import { defineProps, reactive, useContext } from 'vue'const props = defineProps({ no: String})const state = reactive({ room: {}})const init = async () => { console.log(props.no);}init()</script><style></style>