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

新手上路,请多包涵

喜欢标题,关于链接: script setup (不含参考糖)

 <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>

原文由 moreant 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 987
2 个回答

要将 props 与 <script setup> 一起使用,您需要调用 defineProps() 并将组件 prop 选项作为参数,这将定义组件实例上的 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'
})

原文由 Richard 发布,翻译遵循 CC BY-SA 4.0 许可协议

使用 Vue-3.1 及更高版本的功能非常简单的答案:

CircleImage.view

 <template>
  <div class="px-4 w-8/12 sm:w-3/12">
    <img :src="src" :alt="alt" class="border-none rounded-full h-auto max-w-full align-middle" />
  </div>
</template>

<script setup>
const props = defineProps({
  src: String,
  alt: String,
})
</script>

MyView.view

 <template>
  <div class="flex flex-wrap justify-center">
    <CircleImage src="/file1.jpg" alt="one" />
    <CircleImage src="/file2.svg" alt="two" />
  </div>
</template>

<script setup>
import CircleImage from '@/components/CircleImage.vue'
</script>

另请参阅文档: 声明道具或附加选项

原文由 oHo 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题