Output user first name - laravel

I want to get the name of the user to put it on an h1.
What dies this line stand for?
#select="option => selected = option">
I'm using Buefy for the vue components.
<template>
<section>
<div class="field">
<b-switch v-model="keepFirst">
Keep-first <small>(will always have first option pre-selected)</small>
</b-switch>
</div>
<p class="content"><b>Selected:</b> {{ selected }}</p>
<b-field label="Find a name">
<b-autocomplete
v-model="name"
placeholder="e.g. Anne"
:keep-first="keepFirst"
:data="filteredDataObj"
field="user.first_name"
#select="option => selected = option">
</b-autocomplete>
</b-field>
</section>
</template>
<script>
import data from '#/assets/data_test.json'
// Data example
// [{"id":1,"user":{"first_name":"Jesse","last_name":"Simmons"},"date":"2016-10-15 13:43:27","gender":"Male"},
// {"id":2,"user":{"first_name":"John","last_name":"Jacobs"},"date":"2016-12-15 06:00:53","gender":"Male"},
// {"id":3,"user":{"first_name":"Tina","last_name":"Gilbert"},"date":"2016-04-26 06:26:28","gender":"Female"},
// {"id":4,"user":{"first_name":"Clarence","last_name":"Flores"},"date":"2016-04-10 10:28:46","gender":"Male"},
// {"id":5,"user":{"first_name":"Anne","last_name":"Lee"},"date":"2016-12-06 14:38:38","gender":"Female"}]
export default {
data() {
return {
data,
keepFirst: false,
name: '',
selected: null
}
},
computed: {
filteredDataObj() {
return this.data.filter((option) => {
return option.user.first_name
.toString()
.toLowerCase()
.indexOf(this.name.toLowerCase()) >= 0
})
}
}
}
</script>

# is shorthand for v-on:, so it's handling a select event with a function that receives option as a parameter and assigns it to selected.
Since v-model is bound to name, you should be able to do <h1>{{name}}</h1> to have the same value show up in an H1.
The data section has the main variables for your object. name is there. There is also a computed (named filteredDataObj) that should return an array (length of zero or one) with the matching test data. If you want other fields (like id) you would need to look there. Something like
{{filteredDataObj.length ? filteredDataObj.id : ''}}
would give the id if name matched anything in the data set.

Related

Problem getting updated value from child component to the parent component in a Laravel 9 with Vue

I am using a Laravel 9 application with Vue 3. I have created a fresh install.
I want to create some components that I want to use in a parent component. The first component that I want to create is which will be passed a value (postal code) and the component will format and validate the passed value. The parent component should have access to the updated formatted value.
As a first step, I have created the postal-code-component using the documentation from vuejs.org.
<!-- postalcode.vue -->
<script>
export default {
props: ['modelValue'],
emits: ['update:modelValue'],
computed: {
value: {
get() {
return this.modelValue;
},
set(value) {
this.$emit('update:modelValue', value)
}
}
}
}
</script>
<template>
<input v-model="value" />
</template>
Next, I made a copy of the example-component, that comes with the Laravel Vue installation to create a data element "postalcode" and use as a v-model for ,
<div class="card-body">
<postal-code-input v-model="postalcode" /> {{ postalcode }}
</div>
</template>
<script>
export default {
data(){
return {
postalcode:'l3r3g',
}
},
}
When I run my app, it displays the initial value (l3r3g) in the input box and also the same value at {{postalcode}}. However, when I update the value in the input box, it does not update {{postalcode}} in the parent component. When I inspect the component in vue dev tools, I see that modelValue and computed 'value' are undefined, as shown
I just don't know what is going on. I shall appreciate any help to fix this issue.
I've tried by using watcher instead of computed property because the computed properties made cache and sometime it's set() method created complications in debugging reactivity.
Following snippet works for me:
// PostalCode.vue
<template>
<div class="input-group input-group-merge mb-3">
<input
v-model="postalCode"
type="text" class="form-control"
id="postal_code" name="postal_code"
/>
</div>
</template>
<script>
export default {
name: "PostalCode",
props: {
modelValue: String,
},
data() {
return {
postalCode: null
}
},
watch: {
// watching prop
modelValue: {
handler: function (newValue) {
if (newValue) {
this.postalCode = newValue;
}
},
immediate: true,
},
// watching data() property
postalCode: {
handler: function (newValue, old) {
this.$emit('update:modelValue', newValue)
},
immediate: true
}
}
}
</script>
Usage:
<postal-code v-model="user.postal_code"/>
Your can also place your formatting logic within any watcher also.
Hint/Suggestion:
depending on requirement, if you want to do formatting on props change by parent (for old and new both) then place formatting logic in modelValue watcher.
Note:
Following snippet works perfectly on Vue3
If you’re using v-model to bind a prop like this
<postal-code-input v-model="postalcode" />
The postal-code component should emit ‘input’ and have a value prop. You can use a different prop and event but then you should avoid the v-model binding and just do something like this
<postal-code-input :modelValue="postalcode" #modelValueUpdate=“handleUpdate” />

Use methods and computed properties in child component

In my List component I have a method which count the length of the array within certain categories.
methods: {
getLengthofaCategory(cat) {
const LowerCaseSearch = this.search.toLowerCase();
let categoryCount = this.products.filter(
product =>
(product.name.toLowerCase().includes(LowerCaseSearch) ||
product.category.toLowerCase().includes(LowerCaseSearch)) &&
(!this.checked.length || this.checked.includes(product.category)) &&
product.category === cat
);
return categoryCount.length;
}
}
See here my setup in this sandbox.
But I want the values next to the checkboxes (which are coming from my CheckBox component).
How do I get the logic from the method getLengthofaCategory into my CheckBox component?
So I am able to use {{ getLengthofaCategory('tennis') }} in the v-for loop, inside the CheckBox component. And then maybe I can also use category.value instead of hardcoding e.g 'tennis' as the paramater?
In your list.vue, you can use the already created computed function filteredData instead of doing the filter again. This saves some performance because in Vue, computed properties are "cached" once run.
So you can create a new computed function that creates an object with keys per category and value can either be just the amount or an array of products in this category.
I would then pass this computed value to the CheckBox component via a prop, then inside the CheckBox component, you can display the .length or value regarding how many items each category has:
List.vue:
computed: {
//...
amountPerCategory() {
return this.filteredData.reduce((categories, product) => {
if (!(product.category in categories)) {
categories[product.category] = [];
}
categories[product.category].push(product);
return categories;
}, {});
}
}
CheckBox.vue:
<span class="ml-2 text-gray-700 capitalize">{{ category.value }}</span> -
<span
v-if="count[category.value]"
class="ml-2 text-gray-700 capitalize"
>{{ count[category.value].length }}</span>
count: {
type: Object,
default: () => ({})
}
https://codesandbox.io/s/admiring-ellis-4hojl?file=/src/components/CheckBox.vue

how to validate 2 fields with Minimum/Maximum compare validation in ionic3?

Working on reactive form group which contain 2 fields such as min and max, data is coming form hard-coded array data . when we enter the value on respective field just want to show validation that min value should be greater than max
Hope this will help you
create a form as bellow
createForm() {
this.personalDataForm = new FormGroup({
fieldOne: new FormControl("", [Validators.minLength(5), Validators.maxLength(15)])
// ...
});
}
add validations to your template
<form [formGroup]="personalDataForm">
<ion-row>
<label class="lbl-lnu">fieldOne :</label>
<input type="text" class="input-lnu" formControlName="fieldOne">
<div class="form-control-feedback" *ngIf="personalDataForm.controls.fieldOne.errors && (personalDataForm.controls.fieldOne.dirty || personalDataForm.controls.fieldOne.touched)">
<p class="error-msg" *ngIf="personalDataForm.controls.fieldOne.errors.minlength">Minimum length is 5</p>
<p class="error-msg" *ngIf="personalDataForm.controls.fieldOne.errors.maxlength">Maximun length is 15</p>
</div>
</div>
</ion-row>
</form>
to fire validation when submit, use bellow function
function isValid(): boolean {
const valid = this.personalDataForm.valid
if (!valid) { // if not valid fire validation
Object.keys(this.personalDataForm.controls).forEach(field => {
const control = this.personalDataForm.get(field);
control.markAsTouched({ onlySelf: true });
});
}
return valid; // if form data valid return true, otherwise false
}

Get index within v-for using computed or method

I was wondering if it is possible in vue to get the index of an object array directly within the v-for in and pass this value to a computed property or a method, similar to this here, or even a computed property
<div v-for="(object, index) in objects(index)"></div>
methods: {
objects(index){
const categoryId = Object.keys(this.data);
return this.data[categoryId[index]].extras;
}
}
I need to have the index as it is more convenient for me to return the correct value based on defined key, is there some way to achieve this?
Transform your data using a computed value and loop over that. I am not sure what your this.data looks like, but something like this should work (tweak it to suit your needs):
<div v-for="object in computed_objects"></div>
computed: {
computed_objects(){
return Object.keys(this.data).map(categoryId => this.data[categoryId].extras)
}
}
You can bind a method call on each element created by the v-for directive, so for example any time a user clicks on <li> element, it will gets the index of that clicked item:
new Vue({
el: '#app',
data: {
clickedIndex: null,
weekDays: ['monday', 'tuesday', 'wednesday', 'thursday', 'friday']
},
methods: {
handleClick(i) {
this.clickedIndex = i;
}
}
})
Vue.config.productionTip = false;
Vue.config.devtools = false;
<script src="https://cdn.jsdelivr.net/npm/vue#2.5.16/dist/vue.js"></script>
<div id="app">
<ul>
<li v-for="(day,i) in weekDays" v-on:click="handleClick(i)">{{day}}</li>
</ul>
<p>Index clicked {{ clickedIndex }}</p>
</div>

vue.js: vue-multiselect, clearing input value after selected

I am working on my project in laravel/vue.js and I decided to use simple vue-multiselect to choose categories from my database. Thing is I want to clear the value from input field (to look for item in list).
My multiselect component:
<multiselect
v-model="value"
placeholder="Find the category"
label="category_name"
:options="categories"
#input="addReceiversFromCategory">
</multiselect>
I try to clear an v-model but it work only on first select after page load (and also it is not a smart way..).
Last thing i try was the :clear-on-select="true" but it works onlu when multiple is true (which I dont want to be true).
I think its simple to do but I didn't find any way in documentation doc
If your v-model is just modeling the value selected, then you need to use that value however you want and reset value to null. I don't really know how your component is set up but it would look something like this:
<template>
<select v-model="value" v-on:change="doSomething()">
<option :value="null">-- Select --</option>
<option value="foo">Foo</option>
<option value="bar">Bar</option>
</select>
</template>
<script>
module.exports = {
data: function(){
return {
value: null
};
},
methods: {
doSomething: function() {
if( this.value ) {
var data = this.value; // now you can work with data
this.value = null; // reset the select to null
}
}
}
}
</script>

Resources