当我在 vue 3 脚本设置中将数组作为 prop 传递时,如何在 DefineProps 中初始化/为数组提供默认值

Swa*_*wal 2 vue.js vue-props vuejs3

我已经传递了一个数组作为道具项,我在接口 Props 中给了它一个类型,当我尝试给它一个默认值时,我得到一个错误第四行我TS2322: Type 'never[]' is not assignable to type '(props: Readonly<Props>) => string[]'. \xc2\xa0\xc2\xa0Type 'never[]' provides no match for the signature '(props: Readonly<Props>): string[]'. 不确定我在这里做错了什么,因为这似乎适用于其他变量

\n
<script setup lang="ts">\nimport {ref} from "vue";\n\ninterface Props {\n  items?: Array<string>\n}\n\nconst props = withDefaults(defineProps<Props>(), {\n  items: []\n});\nlet selectedItem = ref(props.items[0])\n
Run Code Online (Sandbox Code Playgroud)\n

Mic*_*evý 13

必须使用工厂函数返回对象或数组默认值。工厂函数还接收原始 props 对象作为参数。

文档

这适用于选项 API 和组合 API!

const props = withDefaults(defineProps<Props>(), {
  items: () => []
});
Run Code Online (Sandbox Code Playgroud)

再生产