How to make only one element activate vue js? - vue.js

How to make only one element activate vue js?
I have 3 drop-down lists, 3 are activated at once, how do I make sure that only one is activated?
As far as I understand, this needs to be done through a loop, but this framework is not given to me
<tr class="inputs-table">
<td>Type object: </td>
<td>
<div class="select">
<div class="select-header form-control" v-on:click="AddForm">
<span class="select__current">Please select one option</span>
<span class="select__off">х</span>
</div>
<addForm v-if="addedForm" />
</div>
</td>
</tr>
<tr class="inputs-table">
<td>Type business-model: </td>
<td>
<div class="select">
<div class="select-header form-control" v-on:click="AddForm">
<span class="select__current">Please select one option</span>
<span class="select__off">х</span>
</div>
<addForm v-if="addedForm"/>
</div>
</td>
</tr>
import addForm from './modal/addForm.vue';
export default {
name: 'Index',
data() {
return {
addedForm: false
}
},
methods: {
AddForm(){
this.addedForm = true;
},
closeForm() {
this.$parent.addedForm = false;
}
},
components: {
addForm,
}
}

with your question and the given screenshot on the comment section, it seems you implement dropdown list in your addForm component and when you click on <div class="select-header form-control" v-on:click="AddForm"> in "type object" or "Type business-model" component will expand the addForm component and your problem is when you click on one header both addForm components are visible.
In that case, there may be several methods to fix this. One easy way to add numbering to each component and only activate the addForm if number equals.
<tr class="inputs-table">
<td>Type object: </td>
<td>
<div class="select">
<div class="select-header form-control" v-on:click="AddForm(1)">
<span class="select__current">Please select one option</span>
<span class="select__off">х</span>
</div>
<addForm v-if="addedForm === 1" />
</div>
</td>
</tr>
<tr class="inputs-table">
<td>Type business-model: </td>
<td>
<div class="select">
<div class="select-header form-control" v-on:click="AddForm(2)">
<span class="select__current">Please select one option</span>
<span class="select__off">х</span>
</div>
<addForm v-if="addedForm === 2"/>
</div>
</td>
</tr>
import addForm from './modal/addForm.vue';
export default {
name: 'Index',
data() {
return {
addedForm: 0
}
},
methods: {
AddForm(number){
this.addedForm = number;
},
closeForm() {
this.$parent.addedForm = false;
}
},
components: {
addForm,
}
}
Since you are using 3 form element this would be enough but if you are planning to use a dynamic number of components it would be great if you use for a method such as create list for each type object
items: [{id:1, title: 'Type Object'}, {id:2, title: 'Business Model'}]
Then use v-for in your tr component such as,
<tr class="inputs-table" v-for="item in items" key="item.id">
<td>{{item.title}}: </td>
<td>
<div class="select">
<div class="select-header form-control" v-on:click="AddForm(item.id)">
<span class="select__current">Please select one option</span>
<span class="select__off">х</span>
</div>
<addForm v-if="addedForm === item.id"/>
</div>
</td>
</tr>

Related

Validating dynamic array in vuelidate

I am very new to vue and I am trying to validate an array using vuelidate which is used to render a dynamic table. The problem is with the validation() method as I can comprehend.
According to vuelidate docs, https://vuelidate.js.org/#sub-collections-validation, the $each method supports array. When I use it, the validation never fails. However, when I omit $each, and, try to validate first index of the array, it returns as corrected - validation fails.
To be more precise, I am trying to validate each added row(s), and if there's a problem with the validation, it'd add a class to the affected row.
Component App.vue,
This is the HTML code:
<template>
<div>
<br>
<div class="text-center">
<button type="button" class="btn btn-outline-primary" #click="addRow()">Shto</button>
</div>
<br>
<p
v-for="error of v$.$errors"
:key="error.$uid"
>
<strong>{{ error.$validator }}</strong>
<small> on property</small>
<strong>{{ error.$property }}</strong>
<small> says:</small>
<strong>{{ error.$message }}</strong>
</p>
<form name="articles" #submit.prevent="submitForm">
<table class="table table-hover table-responsive">
<thead class="thead-inverse">
<tr>
<th>Nr.</th>
<th class="col-3">Numri</th>
<th class="col-4">Përshkrimi</th>
<th class="col-1">Sasia</th>
<th class="col-1">Çmimi</th>
<th class="col-2">Shuma</th>
<th></th>
</tr>
</thead>
<tbody>
<tr v-for="(item, idx) in items_table" :key="item">
<td>
{{idx+1}}
</td>
<td>
<input v-model="item.part_no" name="part_no[]" class="form-control" type="text" />
</td>
<td>
<textarea v-model="item.part_name" name="part_name[]" class="form-control" type="text"></textarea>
</td>
<td>
<input v-model="item.part_qty" name="part_qty[]" class="form-control " type="number" step="0.01">
</td>
<td>
<input v-model="item.part_price" name="part_price[]" class="form-control" type="number" step="0.01">
</td>
<td>
<input :value="item.part_total" name="part_total[]" class="form-control text-center border-0" style="background-color: transparent; font-size: 18 px;" type="text" disabled>
</td>
<td>
<button type="button" #click="deleteRow(idx)" class="btn btn-danger btn-md btn-block">X</button>
</td>
</tr>
</tbody>
</table>
<div class="text-center">
<button type="submit" name="" id="" class="btn btn-primary btn-lg btn-block">Valido</button>
</div>
</form>
<div class="text-center">
<textarea name="" id="verbose_log" cols="70" rows="15" refs="logg"></textarea>
</div>
</div>
</template>
This is the content from script tag:
<script>
import useVuelidate from '#vuelidate/core'
import { required } from '#vuelidate/validators'
export default {
name: 'App',
setup: () => ({ v$: useVuelidate() }),
validation() {
return {
items_table: {
$each: {
part_no: {
required,
}
}
},
}
},
data() {
return {
items_table: [
{
part_no: '', part_name: '', part_qty: '', part_price: '', part_total: ''
}
],
items_subtotal: 0.00,
items_total: 0.00,
}
},
methods: {
deleteRow(index) {
if(this.items_table.length == 1) {
this.items_table.splice(index, 1);
this.items_subtotal = 0.00;
this.items_total = 0.00;
this.addRow();
} else if(this.items_table.length > 0) {
this.items_table.splice(index, 1);
}
},
addRow() {
this.items_table.push({part_no: '', part_name: '', part_qty: '', part_price: '', part_total: ''});
},
submitForm() {
this.v$.$touch();
//if (this.v$.$error) return;
console.log(this.v$);
document.getElementById('verbose_log').innerHTML = JSON.stringify(this.$data, null, 4);
}
},
computed: {
//
}
}
</script>
For the sake of clarity, I have excluded two methods which calculate line total and the total itself.

Getting the dropdown to show based on an ID in vue

I have 2 pages, one has a list of products and the other one has a bunch of data for that product. There is also a drop-down in the second page.
The problem I'm having is that I'm struggling to get the drop-down to have the selected product selected.
So for example, if I select product 1 from the first page then on the second page the drop-down will show product 1 and if I select product 2 then the drop-down will show product 2.
Here is my code for productIndex.vue
<template>
<div>
<div class="content-header">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h3 class="card-title">Product Index</h3>
</div>
<div class="card-body p-0">
<table class="table table-sm table-hover">
<thead>
<tr>
<th>ID</th>
<th>Product Name</th>
<th style="width: 180px;"></th>
</tr>
</thead>
<tbody>
<tr v-for="product in products">
<td>{{ product.id }}</td>
<td>{{product.name}}</td>
<td class="text-right">
<a #click="goToProductData(product.id)" class="btn btn-xs btn-primary">
Data
</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
props: ['products'],
data() {
return {
}
},
methods: {
goToProductData(product_id){
localStorage.setItem('product', product_id);
window.location = `/product-data`;
}
},
}
</script>
and here is my productData.vue
<template>
<div>
<div class="content-header">
<div class="container">
<div class="card">
<div class="card-body">
<div class="row mb-2">
<div class="col-sm-6">
<label for="product_id_select">Product</label>
<select id="product_id_select" class="form-control select2" style="width: 100%;">
<optgroup v-for="product in selectProducts" :label="customer.text">
<option v-for="p in product.children" :value="p.id">{{ p.text }}</option>
</optgroup>
</select>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
props: ['products'],
data() {
return {
}
},
computed: {
selectProducts() {
let select2Options = [];
Object.keys(this.products).forEach(product => {
let productOptions = [];
this.products[product].forEach(p => {
productOptions.push({ id: p.id, text: p.name });
});
select2Options.push({
text: product,
children: productOptions
});
});
return select2Options;
}
}
}
</script>
You forgot to add the v-model to the select in the second page. You can find some example here.
Your code should be something like:
<select id="product_id_select" v-model="selectedProductId" class="form-control select2" style="width: 100%;">
where selectedProductId is a value in your data (or a computed property) that contains the value inserted into the local storage in the first page

The specified value cannot be parsed, or is out of range in vue

I'm trying to create a form that will update a product's pricing when adding the unit amount of the product and
a price of the product, but when I type into one of my textboxes I end up getting this error
The specified value "unit_product_1" cannot be parsed, or is out of range
I don't know what that means or how to solve it.
Here is my code
<template>
<div class="content-header">
<div class="container">
<div class="row">
<div class="col-sm-12">
<div class="card">
<div class="card-body">
<div class="row">
<div class="col-lg-12">
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Unit</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr v-for="product in products">
<td>{{ product['name'] }}</td>
<td>
<input type="text" class="form-control" v-model="product['unit']">
</td>
<td>
<input type="text" class="form-control" v-model="product['price']">
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default{
props: [],
data(){
return {
products: [],
unit_product_1: null,
price_product_1: null,
}
},
computed:{
},
methods: {
getProducts(){
axios.get(`/api/product/all`).then(response => {
this.products = response.data.products;
});
}
},
mounted() {
this. getProducts();
}
}
</script>
unit_product_1: null,
price_product_1: null
You don't use them anywhere.
If you want to mutate your incoming products, you should make a new POST request and send the data back to the server. In this scenario you must know how the server waits to receive the data and send them back as requested.

Getting a NaN when typing a value

I'm trying to calculate a value from 2 input boxes and then get the total of those input boxes. I'm then trying to get the all my amounts and total them and add them to the subtotal but the issue I'm having is that when I type in a number in the first box my output is NaN instead of 0 and I would like for it to show me a 0 instead.
Here is my code
<template>
<div class="content-header">
<div class="container">
<div class="row">
<div class="col-sm-12">
<div class="card">
<div class="card-body">
<div class="row">
<div class="col-lg-12">
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Unit</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr v-for="product in products">
<td>{{ product['name'] }}</td>
<td>
<input type="text" class="form-control" v-model="unit[product['unit']]" #change="calculateCost(product['name'])">
</td>
<td>
<input type="text" class="form-control" v-model="price[product['price']]" #change="calculateCost(product['name'])">
</td>
<td>
{{ cost[product['name']] }}
</td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td>
Subtotal: {{ subTotal }}
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default{
props: [],
data(){
return {
products: [],
unit: {},
price: {},
cost: []
}
},
computed:{
subTotal(){
if(this.cost!== null)
{
if(Object.keys(this.cost).length !== 0){
return Object.keys(this.cost).reduce((carry, item) => {
carry+= Number(this.cost[item])
return carry;
}, Number(0))
}else{
return 0;
}
}
}
},
methods: {
getProducts(){
axios.get(`/api/product/all`).then(response => {
this.products = response.data.products;
});
},
calculateCost(item){
this.cost[item] = Number(this.unit[item]) * Number(this.price[item]);
},
},
mounted() {
this.getProducts();
}
}
</script>
Almost all type of inputs return a string. You can use
<input type="number" class="form-control" v-model="unit[product['unit']]" #change="calculateCost(product['name'])">
or
<input type="text" class="form-control" v-model.number="unit[product['unit']]" #change="calculateCost(product['name'])">
The problem is the v-model for unit and price are set to the different keys than the one given to calculateCost(), which causes the lookups to fail and results in NaN:
<input v-model="unit[product['unit']]" #change="calculateCost(product['name'])"> ❌
^^^^^^ ^^^^^^
<input v-model="price[product['price']]" #change="calculateCost(product['name'])"> ❌
^^^^^^^ ^^^^^^
<input v-model="unit[product['name']]" #change="calculateCost(product['name'])"> ✅
<input v-model="price[product['name']]" #change="calculateCost(product['name'])"> ✅
Setting the keys to product['name'] ensures the correct lookup for unit and price in calculateCost(). Since the user could enter invalid values (non-numeric strings) or omit a value, it's possible to get NaN, so it would be a good idea to add a NaN-check in calculateCost():
calculateCost(item) {
const unit = Number(this.unit[item]);
const price = Number(this.price[item]);
if (Number.isNaN(unit) || Number.isNaN(price)) return;
this.cost[item] = unit * price;
},
Also, you probably want the cost to react to user input, so switch from #change to #input:
<input v-model="unit[product['name']]" #input="calculateCost(product['name'])">
<input v-model="price[product['name']]" #input="calculateCost(product['name'])">
demo

show and hide dynamic data of a column on button click in Vue and laravel

I have a table where each row has a button 'show details'. I have another div stacked within the table, so on clicking the button I want the table to be displayed in the particular column. But I am not able to point which button is clicked from which row to show and hide the div on the clicked row. Here is my code:
<table class="table nowrap scroll-horizontal-vertical">
<thead>
<tr>
<th>SN</th>
<th>Ward no</th>
<th>Personal details</th>
<th>Social security</th>
</tr>
</thead>
<tbody>
<tr v-for="(pop,index) in population" :key="pop.ward_no">
<td>{{index+1}}</td>
<td>{{ pop.ward_no }}</td>
<td>{{ pop.birth }}</td>
<td>
<a href="#" #click="show(index)" class="btn btn-primary">
Show Details
</a>
//show or hide div below on clicking show details button
<div v-show="showDetails">
<h4>Citizen </h4>
<div class="row">
<div class="col-3">{{pop.female}}</div>
<div class="col-2"> {{ pop.male }}</div>
<div class="col-2"> {{ pop.other }}</div>
</div> <br>
</div>
</td>
<td>
<a href="#" class="btn btn-primary" #click="editModal(pop)">
<i class="fa fa-edit"></i>
</a>
<a href="#" class="btn btn-primary" #click="deletePopulation(pop.ward_no)">
<i class="fa fa-trash"></i>
</a>
</td>
</tr>
</tbody>
</table>
This is my vue code:
export default {
data(){
return{
editMode: false,
showDetails: false,
population:{}
})
}
},
methods: {
show(index){
this.showDetails = true;
},
Your showDetails is global and if you click one, you click, vue will show all elements. Your code must be like this code.
new Vue({
el: '.table',
data: {
populations: [
{ showDetails: false, job: 'A' },
{ showDetails: false, job: 'B' },
{ showDetails: false, job: 'C' }
]
}
});
<script src="https://unpkg.com/vue#2.5.2/dist/vue.min.js"></script>
<table class="table">
<tbody>
<tr v-for="(pop, index) in populations">
<td><p v-show='pop.showDetails' class="Detail">My Details</p></td>
<td><a #click="pop.showDetails = false">hide Details</a></td>
<td><a #click="pop.showDetails = true">show Details</a></td>
</tr>
</tbody>
</table>