[Vuejs]-How to declare local property from composition API in Vue 3?

2👍

It seems the result of defineProps is not assigned as a variable. check Vue3 official doc on defineProps. Not really sure what is the use case of ref() here but toRef API can be used as well.

import { ref } from 'vue';
const props = defineProps({ 'initialCounter': Number })
const counter = ref(props.initialCounter)

1👍

Retrieving a read-only value and assigning it to another one is a bad practice if your component is not a form but for example styled input. You have an answer to your question, but I want you to point out that the better way to change props value is to emit update:modalValue of parent v-model passed to child component.

And this is how you can use it:

<template>
    <div>
        <label>{{ label }}</label>
        <input v-bind="$attrs" :placeholder="label" :value="modelValue" @input="$emit('update:modelValue', $event.target.value)">
        <span v-for="item of errors">{{ item.value }}</span>
    </div>
</template>

<script setup>
defineProps({ label: String, modelValue: String, errors: Array })
defineEmits(['update:modelValue'])
</script>

v-bind="$attrs" point where passed attributes need to be assigned. Like type="email" attribute/property of a DOM element.

And parent an email field:

<BaseInput type="email" v-model="formData.email" :label="$t('sign.email')" :errors="formErrors.email" @focusout="validate('email')"/>

In this approach, formdata.email in parent will be dynamically updated.

👤Mises

Leave a comment