VueJS - reusing prop (field name) at definition of other bindigns - vue.js

I don't know how to exactly name this, I have some sort of forms in Vue which consist of different input types or more complex wrapped elements or even custom components. They all have one thing in common though - their fieldName which is used for checking various stuff such as validation, class binding etc.
Example:
<div class="field">
<div class="label">Product name</div>
<input :value="productName" #input="valueChanged" :class="{ changed: isChanged('productName') }" data-field="productName">
</div>
As you can see, productName is repeated 3 times in just a single line. I use it in dataset so valueChanged method (a global mixin) knows that field name has changed, then in the class binding to check if value has changed to style it properly, and next for the value binding itself.
It grows bigger and bigger as I want to add for example another class binding like error: hasErrors('productName')
Is there any way to define the field name once and re-use it in other bindings? It would still require some repetition, but at least changing the field name in the future would be just one change instead of 4-5. Something like this:
<input :fName="productName" :value="fName" #input="valueChanged" :class="{changed: isChanged(fName), error: hasErrors(fName)" :data-field="fName">
I know that wrapping it in some custom component would probably be one way, but that would require a lot of different conditions to render things correctly as I'm using various field types with different structures. And I would need to re-write half of my app.

Here are two potential solutions:
Use v-bind and generate an object with all of the attributes you need
<input v-bind="getAttrs('productName')" #input="valueChanged" />
...
methods: {
getAttrs(fieldName) {
return {
value: this[fieldName],
class: {
changed: this.isChanged(fieldName),
error: this.hasErrors(fieldName)
},
'data-field': fieldName
}
}
}
Store all the fields in a variable and loop through them:
<div
v-for="field in fields"
class="field"
>
<div class="label">
Product name
// Or e.g. {{ field.label }} if you have an array of field objects
</div>
<input
:value="getValue(field)"
:class="{ changed: isChanged(field), error: hasErrors(field) }"
// Still need to use v-bind to generate the data attribute on the fly
v-bind="getDataAttr(field)"
#input="valueChanged"
/>
</div>
...
data() {
return {
fields: [
'fieldName1',
'fieldName2',
'fieldName3'
],
}
},
methods: {
getValue(fieldName) {
return this[fieldName];
},
getDataAttr(fieldName) {
return {
'data-field': fieldName
}
}
}

I believe that having custom component handling input fields is the smartest way. I don't think, there would be that much conditions and even if there is some workaround, you will still need to rewrite half of your app. You may use input type as prop, so you can use component for different field types and if there are much different structures, you can use slots, to add some custom structure.

Related

Formatting rows in Quasar Table based on prop item

Using q-table I'm trying to format specific rows based on the name it contains, however somehow the table is not being displayed when I add computed class as class binding.
Is there a way to make it work so that multiple conditions for class binding can be used?
Here
https://codepen.io/pokepim/pen/wvGWNEp
You can see that the table is not loading when this computed class binding is used.
Your codes invoked this.props.row.name inside computed property is wrong usage.
The context of computed property is the instance of current component, not q-tr context, so this.props.row doesn't exist.
The correct usage will be pass props.name of v-slot:body="props" into one method, inside that method returns the class name you expected based on different conditions.
For example (The codepen):
The template:
<template v-slot:body="props">
<q-tr :props="props" :class="tableFormat(props.row.name)">
<q-td v-for="col in props.cols" :key="col.name" :props="props">{{ col.value }}</q-td>
</q-tr>
</template>
The scripts:
{
methods: {
tableFormat: function (name) {
return name ? 'text-bold' : ''
}
}
}

How create a v-model modifier to a VueJS Component?

In VueJS there is some v-model modifies that pre-parse the binded value, for instance v-model.trim that removes whitespaces from the string.
How can I create my own modifier? for instance v-model.myparse
Today um using something like:
computed: {
name: {
get: function () { return parse(this._name);},
set: function (value) { _name = parse(value);}
}
What is very verbose.
I would it to be reusable to do something like:
<input v-model.myparse="name" name='n1'/>
<input v-model.myparse="name" name='n2'/>
<input v-model.myparse="name" name='n3'/>
<input v-model.myparse="name" name='n4'/>
computed properties with setters seems to do part of the work, but it is really useful with some few variables only, it becomes very verbose with a lot of properties.
First, adding adding a custom modified to v-model is under discussion but not yet implemented.
If it was implemented, you could extend the v-model and add a modifier to it.
Since that is not possible, you have a couple of options left, one of which is to use :value instead of v-model. Because v-model is just a syntactic sugar of following:
<input type="text" :value="message" #input="message = $event.target.value">
The above code is the same as:
<input type="text" v-model="message">
So, I suggest you replace the logic for the #input to something like this:
<input type="text" :value="message" #input="getModel">
Now, you can use a function to return a modified value as:
methods: {
getModel ($event) {
return $event.target.value.trim()
}
}
But all of what I mentioned can still be done with the v-model if you use a function.
Of course it goes without saying, you can create your own custom directive also.

React - Mobx Validation input Field

I have been searching for a MOBX validation on a input field, but I havent be able to find anything, I found "MobX-input" which requires a form but I dont have any form. another one that I found was "mobx-react-form" with ValidatorJs which again uses form. any hint or example would be appreciated . I just wanna be able to use it on plain input field
<Input placeholder="FirstName" type="text"
defaultValue={Contact.FirstName} onChange={(e) => handler(e)} />
Simple validation is pretty easy to create on your own with MobX. For a single field like this, a simple method for validating the function could look like this:
in the component we have an error field that only shows if the input has been submitted (which could be triggered by a button push or whatever)
return <div>
<input placeholder="FirstName" type="text"
defaultValue={Contact.FirstName} onChange={(e) => handler(e)} />
{submitted && <span className="error-message">{Contact.FirstNameError}</span>}
</div>;
In the observable class (I used the non-decorator style), we define the field as an observable, and an error message class as a computed value.
class Contact {
constructor() {
extendObservable({
submitted: false,
FirstName: observable(),
FirstNameError: computed(() => {
if(this.FirstName.length < 10) {
return 'First name must be at least 10 characters long';
}
// further validation here
return undefined;
})
})
}
}
You could easily add an extra hasError computed value that just checks to see if FirstNameError has a value.
This method scales to a few inputs. If you start having a bunch of them, then you'd want to look into an abstraction like a 3rd party library or something you write yourself to manage your validations. You could write a function to generate the computed properties you need based on a little configuration.

Update template with model changed from input vueJS

I'm developing my first app in vueJs and laravel.
now I 'have a problem with v-model.
I have a page with component Person that edit or create new Person.
So I get from my backend in laravel or Model Person or new Person.
Now in my frontend I pass data to component by props:
Page.blade.php
<Person :person-data="{!! jsonToProp($person) !!}"></Person>
(jsonToProp transform model coming from backend in json)
In this case, I would return new Model so without properties, so $person will be a empty object.
Person.vue
<template>
<div>
<label for="name_p"> Name</label>
<input id="name_p" v-model="person.name" class="form-control" />
<button v-on:click="test()">test</button>
{{person.name}}
</div>
</template>
<script>
export default {
props: ['personData'],
mounted() {
},
data() {
return {
person: this.personData
}
},
methods:{
test(){
console.log(this.person.name);
}
}
}
</script>
Now if I change input with model v-model="person.name" I would print name in template but it doesn't change.
But if I click buttonit console write right value.
So I read that changing model value is asynch, so How I can render new Model when change input?
You should declare all the properties up front, as per the documentation:
Why isn’t the DOM updating?
Most of the time, when you change a Vue instance’s data, the view updates. But there are two edge cases:
When you are adding a new property that wasn’t present when the data was observed. Due to the limitation of ES5 and to ensure consistent behavior across browsers, Vue.js cannot detect property addition/deletions. The best practice is to always declare properties that need to be reactive upfront. In cases where you absolutely need to add or delete properties at runtime, use the global Vue.set or Vue.delete methods.
When you modify an Array by directly setting an index (e.g. arr[0] = val) or modifying its length property. Similarly, Vue.js cannot pickup these changes. Always modify arrays by using an Array instance method, or replacing it entirely. Vue provides a convenience method arr.$set(index, value) which is just syntax sugar for arr.splice(index, 1, value).
That may be because your data, which comes from jsonToProp($person) does not reactive.
You see, vue modify each object to make it 'reactive', some times you need to modify it by your own. detection caveats
Try to do this.person = Object.assign({}, this.person, this.personData) in your mounted hook, to make it reactive.

closure within v-for, attribute interpolation

I have this basic setup
<div v-for="n in 4">
<some-component #on-some-event="onSomeEvent(n)"></some-component>
</div>
the on-some-event is dispatched within some-component. but I need to know which of these components sent the message. with the setup above, only n is passed into the method. and the data that the event sends is nowhere.
I'd like to interpolate the function so that the method looks like this
onSomeEvent(n){
return (obj)=>{
console.log(`component ${n} sent ${obj}`);
};
}
but wrapping onSomeEvent with {{}} throws a warning: attribute interpolation is not allowed in Vue.js directives and special attributes.
I could just pass the n index into the component but that seems less elegant because I may not have the ability to modify some-component
I am somewhat new to Vue, so perhaps I am missing some core functionality for this type of thing?
<div v-for="n in 4">
<some-component #on-some-event="onSomeEvent | pass n"></some-component>
</div>
....
filters: {
pass(handler, n) {
return function() {
handler()(n, ...arguments)
}
}
},
methods: {
onSomeEvent() {
console.log(...arguments)
}
}
https://jsfiddle.net/2s6hqcy5/2/
You didn't miss anything, the message is correct, in Vue, you won't be able to use interpolation like that.
http://vuejs.org/guide/syntax.html#Interpolations
However, you may want to change how you manage events and pass data between components. In your example, you can just bind the data like this:
<div v-for="n in 4">
<some-component :n="n"></some-component>
</div>
In your component, declare the prop:
Vue.component('some-component', {
props: ['n'],
...
Now, inside each component, you have the n available like any other property (http://vuejs.org/guide/components.html#Props).
Then when dispatching your event, you can call it like this, with no need for a param:
onSomeEvent()
On the event itself, you can access the n:
console.log('Component' + this.n + ...)
https://jsfiddle.net/crabbly/mjnjy1jt/