binding attributes in vuejs component - laravel-5.3

I am trying to use the last version of vuejs with Laravel 5.3 ! The idea I am trying to fulfill is make a component foreach user. So that I have all users listed and foreach one there is a button "edit" , when I click this button I should see the form to update this user.
So this is how I defined the component :
<script>
new Vue({
el: '.view-wrap',
components: {
user-view: {
template: '#user-view',
props: ['user']
}
},
data: {
users: <?php echo json_encode($users); ?>,
},
methods: {
showForm: function(number){
$('div.update-user-'+number).css({'display':'block'});
},
getClassName: function (index) {
return "update-user-"+index;
},
getUpdateUrl: function(id){
return '/users/update/'+id;
},
}
});
This is the template for the "user-view" which take a class name "updateClass" which contains the id of every user (for show/hide purposes), an "updateUrl" which is the url to update the user to bind it with each form action and finally the object user :
<template id="user-view">
<div>
<div class="updateclass">
<form class="form-horizontal" method="PUT" action="updateUrl">
{{ csrf_field() }}
<ul>
<li>
<label for="name"> Name </label>
<input type="text" name="name" :value="user.name">
</li>
<li>
{!! Form::submit('Save', ['class' => 'button-green smaller right']) !!}
</li>
</ul>
{!! Form::close() !!}
</div>
and This is finally how I call the template :
<user-view v-for="user in users" :updateclass="getClassName(user.id)" :user="user" :updateUrl="getUpdateUrl(user.id)"></user-view>
The issue then : it seems that for example [class="updateclass"] doesn't change the value of updateclass with the result of getClassName(user.id) as defined in template call that is binded to. When I try it with [:class="updateclass"] in the template I get : Property or method "updateclass" is not defined on the instance ...
and the same thing applies to all other binded attributes.

The syntax you are using to assign a class dynamically is wrong. from the getClassName method you have to return a object having className like this : {"className: true} , like following
getClassName: function (index) {
var tmp = {}
var className = 'update-user-'+index
tmp[className] = true
return tmp
}
Than you can assign it like following as is in documentation:
<div :class="updateclass"></div>

Related

Replacing $children in vue 3

I'm currently using vue 2 (with Nuxt).
I have 2 custom components (Form and ErrorMessage) that can be used like this:
<Form>
<div>
<input type="text" name="Name" autocomplete="off" v-model="name">
<ErrorMessage v-model="name" required minlength="4"></ErrorMessage>
<div>
</Form>
In <ErrorMEssage>, I have a validate method:
export default {
methods: {
validate() {
// someLogic
}
}
Inside <Form>, I have a submitHandler method that will loop through every <ErrorMessage> to call its validate:
<template>
<form ref="form" #submit.prevent="submitHandler">
<slot></slot>
</form>
</template>
<script>
export default {
submitHandler() {
this.$children.forEach(c => {
c.validate()
})
}
}
</script>
This works fine as $children can loop through all <ErrorMessage> even if they are nested deeply in multiple divs.
So my question is, how can I do the same in vue3 since $children is removed?
In Vue 3 the $children attribute has been removed and replaced by using $refs
To forEach through a child component you need a ref attribute on your element and then use this.$refs.refName.forEach since you already have ref=form then this.$refs.form.forEach will work for your application

How to dynamically set 'was-validated' class on form to show validation feedback messages with angular 5 after submit

I am using a template based form in angular. I also use bootstrap (v4) and I wish to show some validation messages when the form was submitted.
This is my form:
<form [ngClass]="{'was-validated': wasValidated}">
<div class="form-group">
<label for="name">Name</label>
<input type="text" id="name" name="name" class="form-control" [(ngModel)]="category.name" #name="ngModel" required maxlength="100"/>
<div *ngIf="name.invalid" class="invalid-feedback">
<div *ngIf="name.errors.required">
Name is required.
</div>
</div>
</div>
<button type="submit" class="btn btn-success" (click)="save()">Save</button>
</form>
My component looks as follows:
category: Category;
wasValidated: boolean = false;
ngOnInit() {
this.reset();
}
save() {
this.wasValidated = true;
this.categoriesService.createCategory(this.category).subscribe(
() => {
this.notificationService.add(notifications.category_saved, {name: this.category.name});
this.reset();
},
() => this.notificationService.add(notifications.save_category_failed)
);
}
reset() {
this.wasValidated = false;
this.category = {} as Category;
}
This works, but I have a feeling it's overly complex and more like a workaround rather than the right way. What is the best way to accomplish this?
Note: the class was-validated must be present on the form element in order to show the div with class invalid-feedback. I'm using this: https://getbootstrap.com/docs/4.0/components/forms/#validation
Note 2: I have currently no mechanism yet to prevent form submission on error. I'd like to know a good solution for that as well!
With the answer from #Chellappan V I was able to construct the solution I wanted.
I have applied to following changes:
First added #form="ngForm" to the form tag in the template. Secondly I changed the ngClass expression to reference the submitted state of the form, rather than referring to a boolean which was set to true manually when form was submitted. Last but not least I pass the form in the submit method on the save button.
<form novalidate #form="ngForm" [ngClass]="{'was-validated': form.submitted}">
<!-- form controls -->
<button type="submit" class="btn btn-success" (click)="submit(form)">Save</button>
</form>
In the component I injected the template variable in the component with #ViewChild.
#ViewChild("form")
private form: NgForm;
The submit method now takes a form parameter of type NgForm which is used to check if the form was valid before sending a request to the backend:
submit(form: NgForm) {
if (form.valid) {
this.categoriesService.createCategory(this.category).subscribe(
() => {
this.notificationService.add(notifications.category_saved, {name: this.category.name});
this.reset();
},
() => this.notificationService.add(notifications.save_category_failed)
);
} else {
this.notificationService.add(notifications.validation_errors);
}
}
Finally the reset method resets the form and the model so it can be re-entered to submit a next instance:
reset() {
this.form.resetForm();
this.category = {} as NewCategoryDto;
}

Error : document.queryselector is not a function

In the code below, the button labeled Add More is not functioning as expected. Ideally it should add the input value to the unordered list on the page. Instead, I get the following error:
Uncaught TypeError: document.queryselector is not a function
Page Code
<div id="root">
<input type="text" id="input" v-model="message"/>
<p>The value of the input is : {{message}}</p>
<ul>
<li v-for="n in names" v-text="n"></li>
</ul>
<input id="input1" type="text"/>
<button id="button"> Add More </button>
</div>
<script>
var app = new Vue ({
el : '#root',
data : {
message : 'Hello World!',
favourite : 'author',
names : ['Sunil' , 'Anis' , 'Satyajit']
},
});
document.queryselector('#button').addEventListener('click', function(event) {
var n = document.queryselector('#input1');
app.names.push(n.value);
n.value = '';
});
</script>
Its document.querySelector. Note the capital S in querySelector.
You also have a mispelling with addEventListner. It should be addEventListener.

Meteor - checkbox is maintaining old value

I am new to Meteor :)
I have a template helper:
userRoleMap: function() {
var u = getUser();
if (u) {
var lstRoles = Meteor.roles.find({}).fetch();
var userRoles = u.roles ? u.roles : [];
_.map(lstRoles, function(r) {
_.extend(r, {
userMapped: _.contains(userRoles, r.name)
});
return r;
});
return lstRoles;
}
return [];
}
I am using this helper in my template as:
{{#each userRoleMap}}
<div class="checkbox">
<label>
<input type="checkbox" class="chkUserRole" value="{{name}}" checked="{{userMapped}}"> {{name}}
</label>
</div>
{{/each}}
I am showing the above html/template in a bootstrap-modal. I am showing this modal on click of a button (and setting user-id in a Session which I am using when calling getUser() function).
The issue is the checkbox check state is not changing based on value of "userMapped". It is getting set correctly first time, but not afterwards. The helper userRoleMap is getting called every-time I open modal, but the checkboxes are having same checked state which they had when it was opened previously (manual checks/unchecks are getting maintained).
The return value of helper method is working as expected (verified by logging it on console).
Anything I am missing here ? Something to do with _.extend() ?
The Meteor way to do this is to either return checked as an element attribute or not:
Template.registerHelper( 'checked', ( a, b ) => {
return a === b ? 'checked' : '';
});
{{#each userRoleMap}}
<div class="checkbox">
<label>
<input type="checkbox" class="chkUserRole" value="{{name}}" {{checked userMapped true}}> {{name}}
</label>
</div>
{{/each}}

Reuse Meteor template as inclusion with different helpers

I'd like to re-use a Meteor template as an inclusion (i.e. using {{> }}) in two different contexts. I know I can pass in different data with the inclusion by using {{> templateName data1=foo data2=bar}}, but I'm struggling to figure out how I can provide different helpers based on the context. Here's the template in question:
<template name="choiceQuestion">
<div class="choice-grid" data-picks="{{numberOfPicks}}" data-toggle="buttons">
{{! Provide for the user to make multiple selections from the multiple choice list }}
{{#if hasMultiplePicks}}
{{#unless canPickAll}}<span class="help-block text-center">Pick up to {{numberOfPicks}}</span>{{/unless}}
{{#each choices}}
<label class="btn btn-default"><input type="checkbox" class="choice" name="{{this}}" autocomplete="off" value="{{this}}" checked="{{isChecked}}"> {{this}}</label>
{{/each}}
{{/if}}{{! hasMultiplePicks}}
{{#if hasSinglePick}}
{{#each choices}}
<label class="btn btn-default"><input type="radio" class="choice" name="{{this}}" id="{{this}}" autocomplete="off" value="{{this}}" checked="{{isChecked}}"> {{this}}</label>
{{/each}}
{{/if}}{{! hasSinglePick}}
</div>
</template>
and here's how I've reused it:
{{> choiceQuestion choices=allInterests picks=4}}
The key component of the template is a checkbox. In one context, it will never be checked. In another, it may be checked based on the contents of a field in the user document. I've added checked={{isChecked}} to the template. I've read this boolean attribute will be omitted if a falsey value is returned from the helper which should work well for my purposes.
The template's JS intentionally does not have an isChecked helper. I had hoped I could provide one on the parent where the template is included in the other context in order to conditionally check the box by returning true if the checked conditions are met, but the template doesn't acknowledge this helper.
Here's the template's JS:
Template.choiceQuestion.helpers({
hasSinglePick: function() {
return this.picks === 1;
},
hasMultiplePicks: function() {
return this.picks > 1 || !this.picks;
},
numberOfPicks: function() {
return this.picks || this.choices.length;
},
canPickAll: function() {
return !this.picks;
},
});
and the parent's JS:
Template.dashboard.helpers({
postsCount: function() {
var count = (Meteor.user().profile.posts||{}).length;
if (count > 0) {
return count;
} else {
return 0;
}
},
isChecked: function() {
return (((Meteor.user() || {}).profile || {}).contentWellTags || []).indexOf(this) > -1 ? 'checked' : null;
}
});
Template.dashboard.events({
'click .js-your-profile-tab': function(){
facebookUtils.getPagesAssumeLinked();
}
});
I've tried a few other approaches as well. I tried passing the helper to the template along with the other context (i.e. {{> templateName data1=foo data2=bar isChecked=isChecked}}. This kinda works, but it calls the helper immediately. This breaks these since I need to use a value from the context to determine what to return from my helper. Since this value doesn't exist when the function returns, the function always returns undefined.
If I return a function from this helper rather than the value and then pass the helper into the template inclusion along with the data context, I get better results. In fact, my console logs show the desired output, but I still don't end up with the checked box I expect.
Here's what that looks like. Returning a function:
isChecked: function() {
var self = this;
return function() {
return (((Meteor.user() || {}).profile || {}).contentWellTags || []).indexOf(this) > -1 ? 'checked' : null;
};
}
and passing that to the template:
{{> choiceQuestion choices=allInterests picks=4 isChecked=isChecked}}
Is there an established pattern for overriding template helpers from the parent or for including helpers on the parent that are missing from the child template? How can I achieve this?

Resources