Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set the local default value in defineProps?

I've trying to set the default value of a prop to a local value using i18n. I'm using Vue 3.2 and the script setup tag.

I've tried the following but this gives me an error:

defineProps are referencing locally declared variables.

<script setup>
import { useI18n } from 'vue-i18n';
    
const { t } = useI18n();
    
defineProps({
  type: { type: String, required: true },
  title: { type: String, required: false, default: `${t('oops', 1)} ${t('request_error', 1)}` },
  description: { type: String, required: false, default: '' },
  showReload: { type: Boolean, required: false, default: false },
  error: { type: String, required: true },
});
</script>

What's the best way to handle this?

like image 539
Thore Avatar asked Sep 13 '25 10:09

Thore


2 Answers

How to define props with default ( reference locally declared variables )

The solution is to import i18n and use it directly.

import { useI18n } from 'vue-i18n'


export interface Props {
  msg?: string
}

const props = withDefaults(defineProps<Props>(), {
  msg: () => useI18n().t('message')
})

In this solution you don't lose reactivity

I should mention that you can import i18n like this from your defined messages file.

import i18n from '@/plugins/i18n'

const { t } = i18n.global

How to define props with default

If you want Default props values when using type declaration use this:

export interface Props {
  msg?: string
  labels?: string[]
}

const props = withDefaults(defineProps<Props>(), {
  msg: 'hello',
  labels: () => ['one', 'two']
})

Read this question

Learn more here

like image 108
sadeq shahmoradi Avatar answered Sep 16 '25 06:09

sadeq shahmoradi


defineProps is a compiler macro, so you can't use any runtime values within it. I'd suggest to use a local variable for this default:

<script setup>
    import { useI18n } from 'vue-i18n';

    const props = defineProps({
        type: { type: String, required: true },
        title: { type: String, required: false},
        description: { type: String, required: false, default: '' },
        showReload: { type: Boolean, required: false, default: false },
        error: { type: String, required: true },
    });


    const { t } = useI18n();
    const titleWithDefault = props.title || `${t('oops', 1)} ${t('request_error', 1)}`;
</script>

Also described here in the last bullet point: https://v3.vuejs.org/api/sfc-script-setup.html#defineprops-and-defineemits

like image 41
Thomas Avatar answered Sep 16 '25 05:09

Thomas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!