You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue3 Composition API TS组件:setup未定义、props为null的问题咨询

错误原因分析

  • defineProps使用场景错误:defineProps是Vue3 <script setup>语法糖专属API,普通<script>中直接调用无法正确初始化props,导致props为null。
  • setup函数写法错误:普通<script>里的setup函数必须放在export default配置项中,全局作用域直接写setup()会被TypeScript判定为未定义变量。
  • 缺失API导入:使用ref()但未从vue包中导入,会触发未定义错误。

正确实现方案

推荐使用Vue3官方主推的<script setup lang="ts">语法,这是最简洁的Composition API写法,自动处理上下文并支持TypeScript类型推导:

<template>
  <input type="text" v-model="value" placeholder="hello">
</template>

<script setup lang="ts">
import { ref, watch } from "vue";

// 定义Props类型接口
interface SearchProps {
  onChange: (value: string) => void;
  name: string;
  created: string;
}

// 声明并获取props,自动注入组件上下文
const props = defineProps<SearchProps>();

// 组件内部响应式变量,绑定input的v-model
const value = ref('');

// 监听输入值变化,触发父组件传入的回调
watch(value, (newVal) => {
  props.onChange(newVal);
});
</script>

<style scoped>
input {
  width: 300px;
}
</style>

关键代码说明

  • <script setup lang="ts">:自动开启Composition API模式,所有代码默认在setup上下文执行,无需手动编写setup函数。
  • defineProps<SearchProps>():通过泛型直接传入类型接口,Vue会自动推导props的类型约束,同时生成运行时props定义。
  • watch监听逻辑:当输入框值变化时,调用父组件传入的onChange方法,将最新值传递出去,实现组件间通信。

内容的提问来源于stack exchange,提问作者Asking

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 17:35:26