Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Script setup - how to use props in computed

Tags:

vue.js

vuejs3

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

like image 670
berkan Avatar asked May 07 '26 06:05

berkan


1 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

like image 151
tony19 Avatar answered May 09 '26 06:05

tony19