I am using Vite to build my Vue SFCs. I need to access the modelValue
inside a function
declared by the component. How do I do it?
Here is what I tried:
<script setup>
defineProps([ 'modelValue' ]);
defineEmits([ 'udpate:model-value' ]);
function portPlaceholder() {
// ERROR THROWN HERE, modelValue is not defined
if ( modelValue?.type === 'example' ) return 'something';
if ( modelValue?.type === 'other' ) return 'something-else';
return 'default-something';
}
</script>
<template>
Some input: <input type="text" :placeholder="portPlaceholder()" />
</template>
CodePudding user response:
Try to assign the define props to a prop constant the use that constant to access the prop field, and use computed property instead of the function :
<script setup>
import {computed} from 'vue';
const props = defineProps([ 'modelValue' ]);
const emit = defineEmits([ 'udpate:model-value' ]);
const portPlaceholder = computed(()=>{
if ( props.modelValue?.type === 'example' ) return 'something';
if ( props.modelValue?.type === 'other' ) return 'something-else';
return 'default-something';
})
</script>
<template>
Some input: <input type="text" :placeholder="portPlaceholder" />
</template>