#update:modelValue disables field rule validation - vue.js

Given the following component consuming a Vuetify v-text-field
<script setup lang="ts">
const props = defineProps<{
fieldValue: unknown;
}>();
const emit = defineEmits<{
(e: "update:modelValue", newValue: unknown): void;
}>();
</script>
<!-- This validates -->
<!--
<template>
<v-text-field
label="label"
:rules="[ v => !!v || 'Field is required' ]"
:model-value="fieldValue"
/>
</template>
-->
<!-- This does not validate -->
<template>
<v-text-field
label="label"
:rules="[ v => !!v || 'Field is required' ]"
:model-value="fieldValue"
#update:modelValue="emit('update:modelValue', $event)"
/>
</template>
The problem is that when I attach a listener to #update:modelValue the field rules don't work anymore ( I can clear the field and nothing happens ). When I remove #update:modelValue the field rules are working fine.
Reproduction link
Is something wrong with the code or is it a bug?

The :modelValue prop and #update:modelValue event is an expanded form of v-model which is missing in your example.
So, use v-model in your App.vue, like this-
<MyField v-model.field-value="msg" :field-value="msg" />
Edit---
As per your comments, if you cant use v-model then you can follow this guide from the documentation, and use it like this-
App.vue-
<template>
<v-app>
<v-main>
<MyField :field-value="msg" #update:fieldValue="doSomething"/>
</v-main>
</v-app>
</template>
<script setup>
import { ref } from 'vue'
import MyField from './MyField.vue'
const msg = ref('Hello World!')
const doSomething = (event) => { console.log(event) }
</script>
MyFiled.vue-
<script setup lang="ts">
const props = defineProps<{
fieldValue: unknown;
}>();
const emit = defineEmits<{
(e: "update:fieldValue", newValue: unknown): void;
}>();
</script>
<template>
<v-text-field
label="label"
:rules="[ v => !!v || 'Field is required' ]"
:model-value="fieldValue"
#input="$emit('update:fieldValue', $event.target.value)"
#blur="$emit('update:fieldValue', $event.target.value)"
></v-text-field>
</template>
Working demo

Related

ReferenceError: contenuto_translated is not defined

I'm stuck at this error that I get only if I run my laravel + vuejs in build mode.
Ihave a custom component with 3 input and I'm using it in a Quasar dialog. When I start typing inside one of these 3 inputs, it give me the error I wrote in the post title.
See code and details.
I have a custom component file (EditObjectTranslation_Singleline.vue)
<template>
<q-dialog ref="dialogRef" #hide="onDialogHide">
<q-card class="q-dialog-plugin">
<!--
...content
... use q-card-section for it?
-->
<q-card-section>
<div class="text-h6">{{ titolo }}</div>
<q-form #submit.prevent="invia_form">
<div>
<q-input outlined v-model="contenuto_campo" label="Contenuto CAMPO" class="mt-4 block w-full" :disable="true"/>
</div>
<div>
<q-input outlined v-model="contenuto_lingua_default" label="Contenuto Lingua IT" class="mt-4 block w-full" :disable="true"/>
</div>
<div>
<q-input outlined v-model="contenuto_translated" :label="label_translated" class="mt-4 block w-full" :maxlength="max_lunghezza"/>
</div>
</q-form>
</q-card-section>
<!-- buttons example -->
<q-card-actions align="right">
<q-btn color="primary" label="OK" #click="onOKClick" />
<q-btn color="primary" label="Cancel" #click="onDialogCancel" />
</q-card-actions>
</q-card>
</q-dialog>
</template>
<script setup>
import { useDialogPluginComponent } from 'quasar'
import { computed } from '#vue/reactivity'
const props = defineProps({
contenuto_campo: '',
contenuto_lingua_default: '',
contenuto_translated: '',
lingua: '',
max_lunghezza: 0
})
const label_translated = computed (() => {
return "Contenuto tradotto " + props.lingua
})
defineEmits([
// REQUIRED; need to specify some events that your
// component will emit through useDialogPluginComponent()
...useDialogPluginComponent.emits
])
const { dialogRef, onDialogHide, onDialogOK, onDialogCancel } = useDialogPluginComponent()
// dialogRef - Vue ref to be applied to QDialog
// onDialogHide - Function to be used as handler for #hide on QDialog
// onDialogOK - Function to call to settle dialog with "ok" outcome
// example: onDialogOK() - no payload
// example: onDialogOK({ /*...*/ }) - with payload
// onDialogCancel - Function to call to settle dialog with "cancel" outcome
// this is part of our example (so not required)
function onOKClick () {
// on OK, it is REQUIRED to
// call onDialogOK (with optional payload)
onDialogOK(props)
// or with payload: onDialogOK({ ... })
// ...and it will also hide the dialog automatically
}
</script>
Then, I want to use the previous component as a custom component in a quasar dialog.
So the page code where I'm using the previous custom components follows
<script setup>
import AuthenticatedLayout from '#/Layouts/AuthenticatedLayout.vue';
import { Inertia } from '#inertiajs/inertia';
import { useQuasar } from 'quasar';
import { ref } from 'vue';
import { computed } from '#vue/reactivity';
import { Link } from '#inertiajs/inertia-vue3';
import CustomComponent from '#/Components/EditObjectTranslation_Singleline.vue';
import axios from 'axios';
const $q = useQuasar()
const props = defineProps({
catalogues: Array,
lingue: Array,
field2betranslated: Number
})
const $qTranslate = useQuasar()
function onTranslateObject (pLingua) {
if (selected.value.length > 0 ) {
axios
.get('/api/getTraduzioni/'+ pLingua + '/' + selected.value[0].resource_id)
.then((response) => {
$q.dialog({
component: CustomComponent,
componentProps: {
titolo: 'Traduci contenuti:',
contenuto_campo: selected.value[0].name,
contenuto_lingua_default: response.data.originale,
contenuto_translated: response.data.tradotto,
lingua: pLingua,
max_lunghezza: 64,
resource_id: selected.value[0].resource_id
// ...more..props...
}
}).onOk((formData) => {
// console.log('>>>> OK')
translateObject(formData)
}).onOk(() => {
// console.log('>>>> second OK catcher')
}).onCancel(() => {
// console.log('>>>> Cancel')
}).onDismiss(() => {
// console.log('I am triggered on both OK and Cancel')
})
})
} else {
$q.dialog({
title: 'Attenzione',
message: 'Devi selezionare una riga'
})
}
}
</script>
<template>
<Head :title="$t('cataloghi.pagetitle') " />
<AuthenticatedLayout>
<div class="q-py-xl">
<!-- Pulsanti traduzioni -->
<div class="w-full flex justify-end space-x-2 mb-4">
<q-btn v-for="lingua in lingue" :label="lingua.codiceIso" :key="lingua.codiceIso" #click="onTranslateObject(lingua.codiceIso)" icon="language" color="whte" text-color="text-grey-7" />
</div>
</div>
</AuthenticatedLayout>
</template>
When I open the dialog and try to input in the "contenuto_translated" q-input I get this error:
"ReferenceError: contenuto_translated is not defined"
Surely I'm missing something.
Please help me.

Vue3 - ref to component child from other library

I have a problem. I want to access to original value in input in gmap autocomplete component. Im new in vue 3 and I can't do it. What wrong is here?
<template>
<div class="location-input">
<GMapAutocomplete
class="search"
placeholder="Szukaj..."
ref="autocomplete"
#place_changed="onChange"
>
</GMapAutocomplete>
<font-awesome-icon icon="fa-solid fa-check" style="color: green;"/>
<font-awesome-icon icon="fa-solid fa-xmark" style="color: red;"/>
</div>
</template>
<script setup>
import {defineEmits, ref} from "vue";
let autocomplete = ref(null);
const onChange = async (value) => {
await new Promise(resolve => {
setTimeout(async () => {resolve()}, 1500)
})
// eslint-disable-next-line
console.info(autocomplete.input)
emit('change', value)
}
const emit = defineEmits(['change'])
</script>
GmapAutocomplete component templete:
<template>
<input ref="input" v-bind="$attrs" v-on="$attrs" />
</template>

Show on click / hide on blur wrapper component

I have several widgets that I'd like to toggle on click/blur/submit.
Let's take a simple example with an input (Vue 2 style)
Input.vue
<template>
<input
ref="input"
:value="value"
#input="input"
#blur="input"
#keyup.escape="close"
#keyup.enter="input"
/>
</template>
<script>
export default {
props: ['value'],
methods: {
input() {
this.$emit("input", this.$refs.text.value);
this.close();
},
close() {
this.$emit("close");
},
}
}
</script>
ToggleWrapper.vue
<template>
<div #click="open = true">
<div v-if="open">
<slot #close="open = false"></slot> <!-- Attempt to intercept the close event -->
</div>
</div>
</template>
<script>
export default {
data() {
return {
open: false,
}
},
}
</script>
Final usage:
<ToggleWrapper>
<Input v-model="myText" #submit="updateMyText" />
</ToggleWrapper>
So when I click on ToggleWrapper it appears, but if I close it, it doesn't disappear because it's not getting the close event.
Should I use scoped events ?
How can I intercept the close event by adding the less possible markup on the final usage ?
I think it makes sense to use a scoped slot to do this. But you can also try this kind of solution.
Input.vue
<template>
<input
ref="input"
:value="value"
#input="input"
#blur="input"
#keyup.escape="close"
#keyup.enter="input"
/>
</template>
<script>
export default {
props: ['value'],
methods: {
input() {
this.$emit("input", this.$refs.text.value);
this.close();
},
close() {
this.$parent.$emit('close-toggle')
},
}
}
</script>
ToggleWrapper.vue
<template>
<div #click="open = true">
Click
<div v-if="open">
<slot></slot> <!-- Attempt to intercept the close event -->
</div>
</div>
</template>
<script>
export default {
data() {
return {
open: false,
}
},
created() {
this.$on('close-toggle', function () {
this.open = false
})
}
}
</script>
In a Vue3 style, I would use provide and inject (dependency injection). This solution leaves the final markup very light and you still have a lot of control, see it below :
Final usage :
<script setup>
import { ref } from 'vue'
import ToggleWrapper from './ToggleWrapper.vue'
import Input from './Input.vue'
const myText = ref('hi')
const updateMyText = ($event) => {
myText.value = $event
}
</script>
<template>
<ToggleWrapper>
<Input :value="myText" #submit="updateMyText" />
</ToggleWrapper>
<p>value : {{myText}}</p>
</template>
ToggleWrapper.vue
<template>
<div #click="open = true">
<div v-if="open">
<slot></slot>
</div>
<span v-else>Open</span>
</div>
</template>
<script setup>
import { provide, inject, ref } from 'vue'
const open = ref(false)
provide('methods', {
close: () => open.value = false
})
</script>
Input.vue
<template>
<input
:value="value"
#input="input"
#blur="close"
#keyup.escape="close"
#keyup.enter="submit"
/>
</template>
<script setup>
import { inject, ref } from 'vue'
const props = defineProps(['value'])
const emit = defineEmits(['close', 'input', 'submit'])
const methods = inject('methods')
const value = ref(props.value)
const input = ($event) => {
value.value = $event.target.value
emit("input", $event.target.value);
}
const close = () => {
methods.close()
emit('close')
}
const submit = () => {
emit('submit', value.value)
close()
}
</script>
See it working here

Vue.js: Child component omits the `ref` attribute

I have created a component called Input. All the attributes that are passed to this Input component are inherited successfully, but the ref attribute is always omitted for some reason.
I need the ref attribute to set focus on the element, after the validation fails.
Some.vue
<template>
...
<Input
type="number"
name="mobile"
ref="mobileRef"
v-model="this.form.mobile"
:class="errors.mobile ? 'error' : null"
:error="errors.mobile ?? null"
/>
...
</template>
<script>
import Input from '#Inputs/Input';
export default {
...
components: {
Input,
},
...
}
</script>
Input.vue
<template>
<input
autocomplete="none"
class="form-control"
:ref="ref"
:class="this.class"
:type="this.type ?? 'text'"
:value="modelValue"
:disabled="disabled"
#input="$emit('update:modelValue', $event.target.value)"
/>
</template>
<script>
export default {
name: 'Input',
inheritAttrs: false,
props: ['type', 'class', 'error', 'modelValue', 'disabled', 'ref']
}
</script>
I even hardcoded the ref attribute with some static value, but the result is same, omitted?
What am I doing wrong here..?
ref is a special attribute, it's not supposed to work as a prop.
It's possible to access root element of a component as $refs.mobileRef.$el.focus(). The component can also expose all public methods explicitly, so they would be used as $refs.mobileRef.focus().
You can remove the ref prop in your Input.vue component and add a watcher inside, to watch for some errors. If there is, trigger a .focus() on your input element.
Some.vue
<template>
...
<Input
type="number"
name="mobile"
v-model="this.form.mobile"
:class="errors.mobile ? 'error' : null"
:error="errors.mobile ?? null"
/>
...
</template>
<script>
import Input from '#Inputs/Input';
export default {
...
components: {
Input,
},
...
}
</script>
Input.vue
<template>
<input
autocomplete="none"
class="form-control"
ref="mobileRef"
:class="this.class"
:type="this.type ?? 'text'"
:value="modelValue"
:disabled="disabled"
#input="$emit('update:modelValue', $event.target.value)"
/>
</template>
<script>
export default {
name: 'Input',
inheritAttrs: false,
props: ['type', 'class', 'error', 'modelValue', 'disabled'],
watch: {
error(val) {
if (val)
this.$refs.mobileRef.focus();
},
},
}
</script>

Vue: How do you bind a value to an input through a wrapper component?

I know you can use v-model to bind a value to an input in the same component. How do you create a wrapper component for an input and bind a value to it?
Login.vue
<template>
<div id="Login">
<Input v-bind:value="email"/>
<Input v-bind:value="password"/>
</div>
</template>
<script>
import Input from './Input.vue'
import Button from './Button'
export default {
name: 'Login',
components: {
Input,
Button,
},
data: () => ({
email:'test',
password:'test',
}),
methods: {
login: () => { debugger; }, //this.email and this.password are still set to test
}
}
</script>
Input.vue
<template>
<div class="input>
<input v-model="value"/>
</div>
</template>
<script>
export default {
name: 'Input',
props: {
value: String,
},
}
</script>
Current set up results in
[Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "value"
Is the only way to do this by emitting an event?
If I got it correctly, you can try to create transparent wrapper (in my case AppInput)
SomeParent.vue
<div>
<AppInput v-model="parentModel" />
</div>
AppInput.vue
<template>
<input
class="app-input"
v-bind="$attrs"
:value="value"
v-on="{
...$listeners,
input: event => $emit('input', event.target.value)
}">
</template>
<script>
export default {
name: "AppInput",
inheritAttrs: false,
props: ["value"]
};
</script>
one of articles
The best way is use v-model for wrapper and on/emit for input
<div id="Login">
<Input v-model="email"/>
<Input v-model="password"/>
</div>
...
<div class="input>
<input
v-bind:value="value"
v-on:input="$emit('input', $event.target.value)"
>
</div>
You can implement v-model directly in the input component by doing so.
<template>
<div class="input>
<input :value="value" #input="$emit('input', $event.target.value)"/>
</div>
</template>
<script>
export default {
name: 'Input',
props: ["value"]
}
</script>
And then use it in your parent component like this:
<template>
<div id="Login">
<Input v-model="email"/>
<Input v-model="password"/>
</div>
</template>
<script>
import Input from './Input.vue'
import Button from './Button'
export default {
name: 'Login',
components: {
Input,
Button,
},
data: () => ({
email:'test',
password:'test',
}),
methods: {
login: () => { debugger; }, //this.email and this.password are still set to test
}
}
</script>
See here