要使用“组件”API 和 <script setup> 初始化道具,您需要为 defineProps(...) 宏返回的对象分配一个名称,例如 props 并在引用脚本中的道具时使用该变量名称.所以如果你有一个像这样声明的道具:
const props = defineProps({
position: { type: String, required: false, default: "center middle" },
});
您可以像这样在同一个脚本中使用它:
const myLocation = ref(props.position);
因此,一个完整的示例可能如下所示:
父组件.vue
<template>
<div class="main-body">
<h1>Parent Component</h1>
<div class="grid-container">
<div>
Position (in Parent):
</div>
<div>
<input v-model="msg">
</div>
</div>
<hr>
<div>
<Child :position="msg" title="Child Component 1"/>
</div>
<div>
<Child title="Child Component 2 (default position property)"/>
</div>
</div>
</template>
<script setup>
import { ref } from 'vue'
import Child from './Child.vue'
const msg = ref('North West')
</script>
<style>
.main-body {
margin: 10px 20px;
}
.grid-container {
display: grid;
grid-template-columns: 1fr 2fr;
}
</style>
然后
儿童.vue
<template>
<h2>
{{ title }}
</h2>
<div class="grid-container">
<div>
Position (from parent):
</div>
<div>
{{ position }}
</div>
<div>
My Position:
</div>
<div>
<input type="text" v-model="myLocation">
</div>
<div>
My Position:
</div>
<div>
{{ myLocation }}
</div>
</div>
</template>
<script setup>
import { ref } from 'vue';
const props = defineProps({
position: { type: String, required: false, default: "center middle" },
title: { type: String, required: false, default: "ChildComponent"}
});
const myLocation = ref(props.position);
</script>
<style scoped>
.grid-container {
display: grid;
grid-template-columns: 1fr 2fr;
}
</style>
另外,请在 Vue Playground 中查看此代码
在这个例子中,myPosition 字段是用 prop 初始化的,但是一旦应用程序启动,这个字段就不再依赖于 prop。