Home > Enterprise >  How to declare local property from composition API in Vue 3?
How to declare local property from composition API in Vue 3?

Time:10-17

In Vue 2 I would do this:

<script>
    export default {
      props: ['initialCounter'],
      data() {
        return { counter: this.initialCounter }
      }
    }
</script>

In Vue 3 I tried this:

<script setup>
   import { ref } from 'vue';
   defineProps({ 'initialCounter': Number })
   const counter = ref(props.initialCounter)
</script>

This obviously doesn't work because props is undefined.

How can I bind one-way properties to a local variable in Vue 3?

CodePudding user response:

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)

CodePudding user response:

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.

  • Related