javascript - 如何在 vue3 的 <script setup> 中使用 props

标签 javascript vue.js vuejs3 vue-script-setup

像标题,
关于链接:
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 的 &lt;script setup> 中使用 props,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66382293/

相关文章:

javascript - Vue 3 如何正确更新 Highcharts 中的数据?

javascript - jquery脏表单手动设置干净

javascript - 像这样的东西。getelementbyid(这个div内元素的id)

javascript - 将参数传递给 Vue.js 中 multiselect 的 @select - vue-multiselect

laravel - 使用 Laravel 5.1 和 VueJS 的 TokenMismatchException

javascript - 如何从 Vuejs 应用程序在社交媒体上分享?

javascript - 在javascript中顺利预测鼠标光标的位置

Javascript闭包,调用函数的不同方式

vue.js - Vue js v3 组件无法再访问 $children。我们怎样才能得到一个组件 child ?

typescript - 返回渲染函数(例如 JSX)时,将 vue-devtools 与 composition-api 结合使用