vue: transforms a prop in its definition

Viewed 2832

I've a component which is a button with some stuff like a icon. I use it like this:

<ti-btn icon="..." @click.native="..."></ti-btn>

also, I can pass a prop which isn't required, this prop is the size, which is a Number.

<ti-btn icon="..." size="32" @click.native="..."></ti-btn>

Now, in my component's definition, at first, I wrote:

<template>
   <i :class="icon" :style="{fontSize}"></i>
</template>
<script>
export default {
    props: ['icon', 'size'],
    computed: {
       fontSize() {
           return this.size ? `${this.size}px` : DEFAULT_SIZE;
       }
   }
}
</script>

If the size is not passed down, I set the default value. That's works, but according to good practices and vue style guide, Prop definitions should be as detailed as possible. So, I started to use this way:

props: {
    icon: {
        type: String,
        required: true,
        validate(value){
            //some kind of validation here
            return value.includes('ti')
        }
    },
    size: {
        type: Number,
        required: false,
        default: DEFAULT_SIZE
    }
}

size prop receive a Number, but, it must return a string, in fact DEFAULT_SIZE is set to "24px" which is a String, also, the value receive is transformed to value+"px". So, My question is, how can I transform the size prop in its own definition object, without use the computed property?

1 Answers

As Terry mentioned in the comments, it's not possible to provide a way to transform the value of a prop being passed to a component from within the prop's definition itself.

You could let size just be a Number, and then add the 'px' when you bind it to the style:

<i :class="icon" :style="{ fontSize: `${size}px` }"></i>

This would mean you'd need to make DEFAULT_SIZE equal to 24.


If you're unable to change the value of DEFAULT_SIZE. Then your example of the fontSize computed property is the correct way to handle the issue.

Related