Vue composition typescript access props value in another props validation

143 views Asked by At

i would want to access the props value from another props validator.

Here is my code:

<script lang="ts" setup>
    import { PropType } from 'vue';
    import { iStep } from '@/interfaces/iStep.ts';
    import Step from './Step.vue'

    interface Props {
        steps: string[]|iStep[] ;
        currentStep: number;
    }

    
    const props = defineProps({
        steps: {
            type: [Array as PropType<iStep[]> , Array as PropType<string[]>],
            required: true
        },
        currentStep: {
            type: Number,
            validator: (value: number) => {
                return value >= 1 && value < this?.steps.length;
            }
        }
    });
    
</script>

In the validator this is always undefined and if i try to call it via props const i have an error defineProps() in <script setup> cannot reference locally declared variables because it will be hoisted outside of the setup() function.

I would want to restrict currentStep to be in range 0, props.steps.length.

Any idea how to achieve that ?

And did my steps props declaration type good ?

EDIT:

Access props value in another props' validator doesn't answer my question because in that case it use the option api instead of the api composition from vue (https://vuejs.org/guide/extras/composition-api-faq.html).

1

There are 1 answers

0
Kristofer On

I would suggest putting the validator in a separate function and not mix it with values from a parent component:

const validator = (value: number) => value >= 1 && value < props.steps.length;