如何将空数组绑定到Vue.js3中的props?

ran*_*ool 2 arrays typescript vuejs3 vue-composition-api

<script lang="ts" setup>   
  interface Props {
    bigArray: string[];
  }
        
  ***const props = withDefaults(defineProps<Props>(), {
    bigArray:[],
  }*** <---- Here is the error, setting props
        
  const bigArray = ref(props.BigArray);
</script>
Run Code Online (Sandbox Code Playgroud)

ITsInterface.ts

BigArray?: string[] | null;
Run Code Online (Sandbox Code Playgroud)

在这种情况下寻找将空数组设置为 prop 的正确方法:

  • Vue.js3
  • 组合API
  • 打字稿
  • 在脚本标签中设置

h0p*_*3zZ 10

import { withDefaults, defineProps} from "vue";

interface Props {
    bigArray?: string[]
}

const props = withDefaults(defineProps<Props>(), {
    bigArray: () => []
})

console.log(props.bigArray);
Run Code Online (Sandbox Code Playgroud)

您只需要添加() =>箭头功能即可使其工作。

vue 文档中显示了这一点。

如果您想让 prop 成为可选的(因为它应该具有默认值),请?在变量名称之后使用。这将确保控制台中不会出现不必要的警告。