'Vue3 defineprops usage with v-model in child compoent
As I understand you can not change the props value directly in the child component. But I find out that this will work, I want to know the reason behind it.
For reference: I am using vue3+vite
For example:
<template>
<input v-model="price"/>
</template>
<script lang="ts" setup>
defineProps({
price : Number
});
</script>
this can change the props value based on the input. with no warning or error
but if I write this way
<template>
<input v-model="props.price"/>
</template>
<script lang="ts" setup>
const props = defineProps({
price : Number
});
</script>
there will be a warning in the console.
notice I didn't write any computed to handle the change of the props.
Is it a bad practice?
Solution 1:[1]
Both should issue warning. The reasoning is that the parent will not usualy be aware of the change unless it is mutated there. It also allows the parent to validate the change. The idea is that only the owner of the data should modify it.
So emit an event instead. The conventional way to write the code is.
<input :value="price" @input='$emit("input", $event)'/>
// or
<input :value="price" @update:value='$emit("update:value", $event)'/>
// or
<input :value="price" @input='$emit("update:value", $event)'/>
You can access both because Vue automatically exposes both the props object itself and all the props' properties into the template.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
