Reusable templates and methods? - vue.js

I wish to wrap different types of input with a label and an error message, so far I have come up with this solution, using slots:
Input Text Component: (but there are also others for select, checkbox etc)
<form-input>
<input type="text" #click="doSomething"> //could be select, checkboxes etc. slotted in
</form-input>
Generic Form Input Component:
<div>
<label v-text="label"></label>
<slot></slot> //where each input is placed
<p v-if="hasError">This {{ this.name }} has an error!</p>
</div>
On Input Text Component I also use a mixin that handles all the errors and other form bits, I need to declare this in every different input type, select, checkbox etc.
Is there an easier way to achieve this, I want to:
Wrap various inputs with errors and labels.
Use the same functionality from a mixin (or declared as something else) for every component but not repeat the declaration - I cannot add it on the generic form input component as it is referenced in the data in the parent to be slotted in.

Related

How to use `v-if` and `v-for` on the same element?

Hi I'm trying to figure out how to use v-if on a iterated element which also uses v-for. I need to check if the current element has any of a series of classes, which are numbers.
so the classes of each article would be:
<article class="post-item post-guide 12 22 19 30 55">...
this is the HTML that renders all:
<article v-if="showIfHasClass" :class="'post-item post-guide ' + guide.categories.toString().replace(/,/g, ' ')"
v-for="(guide, index) in guides" :key="index">
<header>
<h1 class="post-title">
{{ guide.title.rendered}}
</h1>
</header>
</article>
I have tried with methods that check the class of all elements, that works, but i'm trying to use a clean Vue built-in solution with v-if without success, i'm not able to retrieve the class of this in a successful way.
Should showIfHasClass be a computed property? I have tried with that too... but it seems, I'm missing something along the way.
my data I have to check against is an array:
data:{
guides: [...]
selectedCategories: [1, 22, 33, 100, 30];
}
or maybe it is better to directly loop over the guides and check if they have the selectedCategory or not, then remove the element from the guides data array?
What is more effective?
Besides the option to create an additional filtered computed (effectively eliminating the need to use v-for and v-if on the same element), you also have a template level way of dealing with such edge-cases: the <template> tag.
The <template> tag allows you to use arbitrary template logic without actually rendering an extra element. Just remember that, because it doesn't render any element, you have to place the keys from the v-for on the actual elements, like this:
<template v-for="(guide, index) in guides">
<article v-if="isGuideVisible(guide)"
:key="index"
class="post-item post-guide"
:class="[guide.categories.toString().replace(/,/g, ' ')]">
<header>
<h1 v-text="guide.title.rendered" />
</header>
</article>
</template>
isGuideVisible should be a method returning whether the item is rendered, so you don't have to write that logic inside your markup. One advantage of this method is that you can follow your v-if element with a fallback v-else element, should you want to replace the missing items with fallback content. Just remember to also :key="index" the fallback element as well.
Apart from the above use-case, <template> tags come in handy when rendering additional wrapper elements is not an option (would result in invalid HTML markup) (i.e: table > tr > td relations or ol/ul > li relations).
It's mentioned here as "invisible wrapper", but it doesn't have a dedicated section in the docs.
Side note: since you haven't actually shown what's inside guide.categories, I can't advise on it, but there's probably a cleaner way to deal with it than .toString().replace(). If guide.categories is an array of strings, you could simply go: :class="guide.categories".
I think the most Vue way is to create a computed property with filtered items from selected categories, then use that in v-for loop (the idea is to move the business logic away from template).
computed: {
filteredItems(){
return this.guides.filter(e => this.selectedCategories.includes(e.category))
}
}
Also, as a note, it is not recommended to use v-if and v-for on the same element, as it may interfere with the rendering and ordering of loop elements. If you don't want to add another level of nesting, you can loop on a 'template' element.
<template v-for="item in items">
// Note the key is defined on real element, and not on template
<item-element v-if='condition' :key="item.key"></item-element>
</template>

Display one object property value, and show another one on hover

the question I have might be hard to understand, so please help me re-organize the question if you can see the better way to put it in.
So, I am building a registration platform.
(1) First, I receive an array of objects of cases the user can sign time to.
(2) Each object consists of 2 properties, "name", "description".
(3) I store the array in the data, end use it in the element provided by a picker called "vue-multiselect", which basically accepts the array and loops over the objects and displays them.
(4) As you can see, it displays both properties and values, which I am trying to avoid. My question is, is it possible to pass only the "name" value into the picker, and display the description value when hovering the first value?
You can find this use case documentation here: https://vue-multiselect.js.org/#sub-custom-option-template
<multiselect v-model="value"
deselect-label=""
select-label=""
placeholder=""
selected-label=""
:show-pointer="true"
:options="projectCases">
<template slot="option" slot-scope="{ option }">
<strong :title="option.description">{{ option.name }}</strong>
</template>
</multiselect>
ps: I use title attribute to implement display-on-hover functionality. you can use any other tooltip library as well.

Vue.js—Difference between v-model and v-bind

I'm learning Vue with an online course and the instructor gave me an exercise to make an input text with a default value. I completed it using v-model but, the instructor chose v-bind:value and I don't understand why.
Can someone give me a simple explanation about the difference between these two and when it's better use each one?
From here -
Remember:
<input v-model="something">
is essentially the same as:
<input
v-bind:value="something"
v-on:input="something = $event.target.value"
>
or (shorthand syntax):
<input
:value="something"
#input="something = $event.target.value"
>
So v-model is a two-way binding for form inputs. It combines v-bind, which brings a js value into the markup and v-on:input to update the js value. The js value must be present in your data, or in an inject.
Use v-model when you can. Use v-bind/v-on when you must :-) I hope your answer was accepted.
v-model works with all the basic HTML input types (text, textarea, number, radio, checkbox, select). You can use v-model with input type=date if your model stores dates as ISO strings (yyyy-mm-dd). If you want to use date objects in your model (a good idea as soon as you're going to manipulate or format them), do this.
v-model has some extra smarts that it's good to be aware of. If you're using an IME ( lots of mobile keyboards, or Chinese/Japanese/Korean ), v-model will not update until a word is complete (a space is entered or the user leaves the field). v-input will fire much more frequently.
v-model also has modifiers .lazy, .trim, .number, covered in the doc.
In simple words
v-model is for two way bindings means: if you change input value, the bound data will be changed and vice versa.
but v-bind:value is called one way binding that means: you can change input value by changing bound data but you can't change bound data by changing input value through the element.
check out this simple example: https://jsfiddle.net/gs0kphvc/
v-model
it is two way data binding, it is used to bind html input element when you change input value then bounded data will be change.
v-model is used only for HTML input elements
ex: <input type="text" v-model="name" >
v-bind
it is one way data binding,means you can only bind data to input element but can't change bounded data changing input element.
v-bind is used to bind html attribute
ex:
<input type="text" v-bind:class="abc" v-bind:value="">
<a v-bind:href="home/abc" > click me </a>
v-model is for two way bindings means: if you change input value, the bound data will be changed and vice versa. But v-bind:value is called one way binding that means: you can change input value by changing bound data but you can't change bound data by changing input value through the element.
v-model is intended to be used with form elements. It allows you to tie the form element (e.g. a text input) with the data object in your Vue instance.
Example: https://jsfiddle.net/jamesbrndwgn/j2yb9zt1/1/
v-bind is intended to be used with components to create custom props. This allows you to pass data to a component. As the prop is reactive, if the data that’s passed to the component changes then the component will reflect this change
Example: https://jsfiddle.net/jamesbrndwgn/ws5kad1c/3/
Hope this helps you with basic understanding.
There are cases where you don't want to use v-model. If you have two inputs, and each depend on each other, you might have circular referential issues. Common use cases is if you're building an accounting calculator.
In these cases, it's not a good idea to use either watchers or computed properties.
Instead, take your v-model and split it as above answer indicates
<input
:value="something"
#input="something = $event.target.value"
>
In practice, if you are decoupling your logic this way, you'll probably be calling a method.
This is what it would look like in a real world scenario:
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<input :value="extendedCost" #input="_onInputExtendedCost" />
<p> {{ extendedCost }}
</div>
<script>
var app = new Vue({
el: "#app",
data: function(){
return {
extendedCost: 0,
}
},
methods: {
_onInputExtendedCost: function($event) {
this.extendedCost = parseInt($event.target.value);
// Go update other inputs here
}
}
});
</script>

Aurelia not outputting attribute with string interpolation in repeat

Is there any reason why a repeat.for binding would remove attributes from elements inside the repeater?
<div repeat.for="i of model.someArray.length">
<label>Some Array - Index ${i + 1}</label>
<input value.bind="model.someArray[i]" some-custom-attribute="someArray[${i}]"/>
</div>
and that some-custom-attribute is not being output within the repeat, but if I were to remove the string interpolation within there then it outputs fine.
== Edit ==
I have put it in a comment but just to make sure everyone is on the same page, ideally this is the output I expect:
<input value.bind="model.someArray[i]" some-custom-attribute="someArray[0]"/>
The some-custom-attribute is not an aurelia attribute, its pure HTML that a 3rd party JS library uses, so the goal here is to get the textual value of the index into the textual attribute value.
model.someArray.length is a number, not an array. You need to iterate over the array. If you do need the current index, the repeater provides the $index property for you to use.
Your code should look like this:
<div repeat.for="item of model.someArray">
<label>Some Array - Index ${$index + 1}</label>
<input value.bind="item" some-custom-attribute.bind="item"/>
</div>
To answer your original question, doing some-custom-attribute="model.someArray[${i}]" makes Aurelia think you are trying to pass a string value to the custom attribute. You can see that in the following gist: https://gist.run/?id=eed8ac8623ff4749aa5bb93c82a7b1fb I've created a custom element that just pushes whatever value it is given in to an element on the page. Note!!! Don't ever do what I'm doing here! I just did this this way so you wouldn't have to open the js console. To actually get a value passed in, you would need to use some-custom-attribute.bind="item" or (to do things how you are doing things, some-custom-attribute.bind="someArray[i]"

ToscaWidgets - customize form

I'm using https://pypi.python.org/pypi/tgapp-resetpassword/0.1.5 which allows you to override the template used for the reset password page. Unfortunately, the actual form itself is included as a 'black box':
<div>
${reset_password_form.display(action=action)}
</div>
The form has been defined as a tw2.forms.TableForm which is not how I'd like to display it. Is it possible to have finer grain control e.g. insert custom html around each of the fields, or be more explicit about how to display certain fields?
E.g. I'd like to do something like the following (made up):
<div>
<form ${reset_password_form.attrs} class="my-own-class-name">
<py:for each="field in reset_password_form.fields">
<div class="custom-class-here">
<label for="${field.id}">
... some logic to possibly override default label else...
${field.default_label_text}
</label>
${field.render_as_input_field()}
</div>
</py:for>
<button type="submit">My own submit text</button>
<form>
</div>
Is this level of customization possible with ToscaWidgets without overriding things in Python?
As by resetpassword documentation you have a reset_password.reset_password_form option that can be used to specify an alternative tw2 form.
You just need to put there the python path (like "resetpassword.lib.forms.ResetPasswordForm") of the form you would like to use in place of the default form.
Then you own form can specify a custom template like https://gist.github.com/amol-/d2a08027d34a8c4dfa69