2
<script setup>
import { defineProps, computed } from '@vue/runtime-core'

defineProps({
  foo: Array,
})

const length = computed(() => {
  return foo.length         // foo is not defined
})
</script>

在这个完全不言自明的块中,当我尝试在计算中到达 props 变量时,会抛出一个错误,例如“未定义 foo”

4

2 回答 2

12

defineProps返回对给定道具的引用,您可以从中foo访问computed

<script setup>
import { defineProps, computed } from 'vue'
        
const myProps = defineProps({
  foo: Array,
})

const length = computed(() => {
  return myProps.foo.length
})          
</script>

演示

于 2021-04-28T21:18:16.753 回答
0

解构道具定义可以清除一些样板代码,并让您在整个脚本中直接访问它们:)

import { computed } from 'vue'
//since I last tested, don't need to import defineProps

const { foo } = defineProps({ 
  foo: Array,
})

const length = computed(() => {
  return foo.length
})          
</script>
于 2022-01-17T22:47:26.747 回答