To add a class programmatically, I can use something like this:
this.$refs.mycells[123].classList.add('my-class')
But, how can I add a v-bind class like this programmatically ?
v-bind:class="{ active: radio == 'link'}"
You can add class like object programatically, just declare a data reactive properties names "cssClass"
data: {
cssClass: {
active: true,
'text-danger': false
}
},
There are two ways you can change using some event trigger methods or
computed properties, when dependent data changes, it updates the value
<div v-bind:class="cssClass">
<button v-on:click="onButtonClick"></button>
</div>
methods: {
onButtonClick() { // if you want ro trigger from
// you can manipulate object
this.cssClass = { active: false, 'text-danger': true }
},
}
Using computed:
<div v-bind:class="setCssClass(true)"></div>
computed: {
setCssClass(val) {
if (val == true) return { active: false, 'text-danger': true };
return { active: false, 'text-danger': true };
}
}
We can bind classes directly in the element or call a function to place appropriate classes.
<p v-bind:class="user.role === 'admin' ? 'is_admin' : 'is_user'"></p>
The same logic can be placed into a function like shown below
<p :class="placeAppropriateClass(user.role)"></p>
//
methods:{
placeAppropriateClass(role){
let addClass = '';
if(role === 'admin'){
addClass = 'is_admin';
}else if(role === 'user'){
addClass = 'is_user';
}else{
addClass='is_guest';
}
return addClass;
}
}
This will add class to p tag according to a conditional statement.
<p class="is_admin"></p>
Related
I would like to create a simple web app that can validation form using Vue?
I have two input fields, firstname[1] and firstname[2]
data: {
firstname: ['',''],
}
I want to use the following code to validate the form, but finally not suessful.
computed: {
missfirstname(){
for(var i=1;i<this.firstname.length;i++){
if(this.firstname[i] =='' && this.attemptSubmit) {
this.firstname_ErrMsg[i] = 'Not be empty';
return true;
}
return false;
}
}
},
methods: {
validateForm: function (e) {
this.attemptSubmit = true;
if(this.missfirstname){
e.preventDefault();
}else{
return true;
}
}
},
Is it possible to use array Loop on the validation form??
here it my code I am using Vue 2
my full code
script.js
var app = new Vue({
el: '#app',
data: {
firstname: ['',''],
firstname_ErrMsg: ['',''],
attemptSubmit: false
},
mounted () {
var self = this;
},
computed: {
missfirstname(){
for(var i=1;i<this.firstname.length;i++){
if(this.firstname[i] =='' && this.attemptSubmit) {
this.firstname_ErrMsg[i] = 'Not be empty';
return true;
}
return false;
}
}
},
methods: {
validateForm: function (e) {
this.attemptSubmit = true;
if(this.missfirstname){
e.preventDefault();
}else{
return true;
}
}
},
})
index.html
<div id="app">
<form action='process.php' method="post" autocomplete="off" name="submit_form" v-on:submit="validateForm">
firstname1 : <input type='text' id='firstname1' name='firstname1' alt='1' v-model='firstname[1]'>
<div v-if="missfirstname">{{firstname_ErrMsg[1]}}</div>
<br><br>
firstname2 :
<input type='text' id='firstname2' name='firstname2' alt='2' v-model='firstname[2]'>
<div v-if="missfirstname">{{firstname_ErrMsg[2]}}</div>
<br><br>
<input id="submit" class="preview_button" name="submit_form" type="submit">
</form>
</div>
<script src='https://cdn.jsdelivr.net/npm/vue#2.7.8/dist/vue.js'></script>
<script src='js/script.js'></script>
Observations :
missfirstname property should be separate for each field else it will be difficult to assign the error for a specific field.
Instead of iterating over a this.firstname everytime in computed property, you can use #blur and check the value for that particular field which user touched.
v-model properties should be unique else it will update other one on changing current one.
Your user object should be like this and you can use v-for to iterate it in HTML for dynamic fields creation instead of hardcoding.
data: {
user: [{
name: 'firstName1',
missfirstname: false
}, {
name: 'firstName2',
missfirstname: false
}]
}
Now, In validateForm() you can just pass the index of the iteration and check the model value. If value is empty, you can assign missfirstname as true for that particular index object in user array.
Update : As per author comment, assigning object in users array via for loop.
data: {
users: []
},
mounted() {
for(let i = 1; i <= 2; i++) {
this.users.push({
name: 'firstName' + i,
missfirstnam: false
})
}
}
The array of javascript start from index 0.
Which means in your missfirstname(), i should be defined with 0
missfirstname(){
for(var i=0;i<this.firstname.length;i++){
if(this.firstname[i] =='' && this.attemptSubmit) {
this.firstname_ErrMsg[i] = 'Not be empty';
return true;
}
return false;
}
}
I am trying to check if an input A is bigger than input B and if this happens disable the button and if it's not enable
Html:
<input v-model="form.a" />
<input v-model="form.b" />
<button :class="{disabled: btnDisabled}">Enviar</button>
VueJs:
<script>
import { required, minLength } from 'vuelidate/lib/validators';
export default {
created() {
},
data: function() {
return {
btnDisabled: false,
form: {
a: '',
b: ''
}
}
},
methods: {
checkEndBillNumber() {
if(this.form.a > this.form.b) {
// I do not know what I should put here
}
else {
// I do not know what I should put here
}
}
}
}
</script>
If you see I do not know what I should and in the vuejs conditional to disable the button if the conditional is true or false.
How can I do that? Thanks!
disabled attribute in buttons get true or false so you can do something like this:
<input v-model="form.a" />
<input v-model="form.b" />
<button :disabled="isDisabled">Enviar</button>
computed: {
isDisabled() {
const result = this.form.a > this.form.b ? true : false;
return result;
}
}
or if you want to add a class you can do this:
<button :class="{ 'yourClassName': isDisabled }">Enviar</button>
Below is vue script - the concern method is called notLegalToShip which checks when age < 3.
export default {
template,
props: ['child', 'l'],
created() {
this.name = this.child.name.slice();
this.date_of_birth = this.child.date_of_birth.slice();
},
data() {
return {
edit: false,
today: moment().format('DD/MM/YYYY'),
childUnder3: false
};
},
computed: {
age() {
var today = new Date();
var birthDate = new Date(this.child.date_of_birth);
var age = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
age--;
}
return age;
}
},
methods: Object.assign(
mapActions(['updateChild']),
{
notLegalToShip() {
if(this.age < 3){
this.childUnder3 = true;
}
this.childUnder3 = false;
},
showForm() {
this.edit = true;
},
hideForm() {
this.edit = false;
},
submitForm() {
this.hideForm();
this.updateChild({
child: this.child,
name: this.name,
dateOfBirth: this.date_of_birth,
childUnder3 : this.childUnder3
});
}
}
)
}
Here's the snippet of my template. The input as below.
I want the notLegalToShip method to be triggered when I click arrow changing the year. A warning will appear when childUnder3 is "true". I've tried #change, #input on my input but my method is not triggered at all:
<div>
{{childUnder3}}
{{age}}
<div class="callout danger" v-if="childUnder3">
<h2>Sorry</h2>
<p>Child is under 3!</p>
</div>
<div v-if="!edit">
<a #click.prevent="showForm()" href="#" class="more-link edit-details edit-child">
<i class="fa fa-pencil" aria-hidden="true"></i>{{ l.child.edit_details }}
</a>
</div>
<form v-show="edit" #submit.prevent="submitForm()">
<div class="input-wrap">
<label for="account__child__date-of-birth__date">{{ l.child.date_of_birth }}</label>
<input id="account__child__date-of-birth__date" type="date" name="date_of_birth" v-on:input="notLegalToShip" v-model="date_of_birth" v-validate="'required'">
<p class="error-message" v-show="errors.has('date_of_birth')">{{ l.child.date_of_birth_invalid }}</p>
</div>
</form>
</div>
Any help checking my code above would be appreciated!
You have a couple of problems...
Initialise the name and date_of_birth properties in the data() initialiser so Vue can react to them. You can even initialise them from your child prop there...
data() {
return {
edit: false,
today: moment().format('DD/MM/YYYY'),
name: this.child.name // no need to use slice, strings are immutable
date_of_birth: this.child.date_of_birth
}
}
Use this.date_of_birth inside your age computed property instead of this.child.date_of_birth. This way, it will react to changes made via your v-model="date_of_birth" input element.
Make childUnder3 a computed property, it will be easier that way
childUnder3() {
return this.age < 3
}
Alternately, ditch this and just use v-if="age < 3"
With the above, you no longer need any #input or #change event listeners.
I am diving into Vue for the first time and trying to make a simple filter component that takes a data object from an API and filters it.
The code below works but i cant find a way to "reset" the filter without doing another API call, making me think im approaching this wrong.
Is a Show/hide in the DOM better than altering the data object?
HTML
<button v-on:click="filterCats('Print')">Print</button>
<div class="list-item" v-for="asset in filteredData">
<a>{{ asset.title.rendered }}</a>
</div>
Javascript
export default {
data() {
return {
assets: {}
}
},
methods: {
filterCats: function (cat) {
var items = this.assets
var result = {}
Object.keys(items).forEach(key => {
const item = items[key]
if (item.cat_names.some(cat_names => cat_names === cat)) {
result[key] = item
}
})
this.assets = result
}
},
computed: {
filteredData: function () {
return this.assets
}
},
}
Is a Show/hide in the DOM better than altering the data object?
Not at all. Altering the data is the "Vue way".
You don't need to modify assets to filter it.
The recommended way of doing that is using a computed property: you would create a filteredData computed property that depends on the cat data property. Whenever you change the value of cat, the filteredData will be recalculated automatically (filtering this.assets using the current content of cat).
Something like below:
new Vue({
el: '#app',
data() {
return {
cat: null,
assets: {
one: {cat_names: ['Print'], title: {rendered: 'one'}},
two: {cat_names: ['Two'], title: {rendered: 'two'}},
three: {cat_names: ['Three'], title: {rendered: 'three'}}
}
}
},
computed: {
filteredData: function () {
if (this.cat == null) { return this.assets; } // no filtering
var items = this.assets;
var result = {}
Object.keys(items).forEach(key => {
const item = items[key]
if (item.cat_names.some(cat_names => cat_names === this.cat)) {
result[key] = item
}
})
return result;
}
},
})
<script src="https://unpkg.com/vue"></script>
<div id="app">
<button v-on:click="cat = 'Print'">Print</button>
<div class="list-item" v-for="asset in filteredData">
<a>{{ asset.title.rendered }}</a>
</div>
</div>
I have a simple table where I would like to handle click elements:
<div class="row"
v-bind:class="{selected: isSelected}"
v-for="scanner in scanners"
v-on:click="scannerFilter">
{{scanner.id}} ...
</div>
JS:
new Vue({
el: "#checkInScannersHolder",
data: {
scanners: [],
loading: true
},
methods: {
scannerFilter: function(event) {
// isSelected for current row
this.isSelected = true;
// unselecting all other rows?
}
}
});
My problem is unselecting all other rows when some row is clicked and selected.
Also, I would be interested to know, it it is possible accessing the scanner via some variable of the callback function instead of using this as I might need to access the current context.
The problem is you have only one variable isSelected using which you want to control all the rows. a better approach will be to have variable: selectedScanner, and set it to selected scanner and use this in v-bind:class like this:
<div class="row"
v-bind:class="{selected: selectedScanner === scanner}"
v-for="scanner in scanners"
v-on:click="scannerFilter(scanner)">
{{scanner.id}} ...
</div>
JS
new Vue({
el: "#checkInScannersHolder",
data: {
scanners: [],
selectedScanner: null,
loading: true
},
methods: {
scannerFilter: function(scanner) {
this.selectedScanner = scanner;
}
}
});
I was under the impression you wanted to be able to selected multiple rows. So here's an answer for that.
this.isSelected isn't tied to just a single scanner here. It is tied to your entire Vue instance.
If you were to make each scanner it's own component your code could pretty much work.
Vue.component('scanner', {
template: '<div class="{ selected: isSelected }" #click="toggle">...</div>',
data: function () {
return {
isSelected: false,
}
},
methods: {
toggle () {
this.isSelected = !this.isSelected
},
},
})
// Your Code without the scannerFilter method...
Then, you can do:
<scanner v-for="scanner in scanners"></scanner>
If you wanted to keep it to a single VM you can keep the selected scanners in an array and toggle the class based on if that element is in the array or not you can add something like this to your Vue instance.
<div
:class="['row', { selected: selectedScanners.indexOf(scanner) !== 1 }]"
v-for="scanner in scanners"
#click="toggle(scanner)">
...
</div>
...
data: {
return {
selectedScanners: [],
...
}
},
methods: {
toggle (scanner) {
var scannerIndex = selectedScanners.indexOf(scanner);
if (scannerIndex !== -1) {
selectedScanners.splice(scannerIndex, 1)
} else {
selectedScanners.push(scanner)
}
},
},
...