Script setup - how to use props in computed

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

defineProps({
  foo: Array,
})

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

In this block which is quite self-explained, when I try to reach props variable in computed, an error throws like 'foo is not defined'

2 Answers

defineProps returns a reference to the given props, from which you could access foo in computed:

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

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

demo

Deconstructing the prop definition gets clear of some boilerplate code, and gives you direct access to them throughout the script :)

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