I'm trying to update a list of products with an editable quantity, which updates and changes a row-wise total of product prices. Please see my code below -
<template>
<div>
<product-search-bar :product_search_route="product_search_route" />
<table class="table table-hover table-responsive table-striped">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Qty.</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr v-for="(product, index) in product_list">
<td>
{{ index + 1 }}
<input type="hidden" :name="'order_items[' + index + '][id]'" :value="product.id" />
</td>
<td>{{ product.name }}</td>
<td>
<input type="number" :name="'order_items[' + index + '][qty]'" #change="product_quantity_changed($event, product)" />
</td>
<td>{{ product.purchase_currency }} {{ product.total_price }}</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
export default {
name: 'form-purchase-order-items',
props: [
'product_search_route',
],
data() {
return {
product_list: []
};
},
mounted() {
},
methods: {
/**
*
* #param product
*/
product_added(product)
{
product.quantity = 1;
product.total_price = product.supplier.purchase_price;
if (!this.product_list.find((v) => { return v.id == product.id }))
this.product_list.push(product);
},
/**
*
* #param product
*/
product_quantity_changed(e, product)
{
var quantity = Number(e.target.value);
this.$set(product, 'quantity', quantity);
this.$set(product, 'total_price', (quantity * product.supplier.purchase_price));
}
},
watch: {
}
}
</script>
The price total does update correctly, seen through Vue DevTools, however, the column <td>{{ product.purchase_currency }} {{ product.total_price }}</td> doesn't reflect the changes made. I've read the documentation and I think this is something that isn't mentioned there.
Edit:
The two members quantity and total_price are being created after the object is received in the product_added(product) callback. This probably makes them non-reactive members of the object.
try #input instead of #change in following html code:
<input type="number" :name="'order_items[' + index + '][qty]'" #change="product_quantity_changed($event, product)" />
I was able to fix this by making quantity and total_price reactive members.
product_added(product)
{
this.$set(product, 'quantity', 1);
this.$set(product, 'total_purchase_price', product.supplier.purchase_price);
if (!this.product_list.find((v) => { return v.id == product.id }))
this.product_list.push(product);
},
Related
I try to make a multiple grid radio with conditions: if one radio button is selected, save it as json with key: question and value: column where the radio button is selected.
<template>
<v-radio-group class="mt-0"
v-model="answer"
:rules="answerRule"
>
<thead>
<tr>
<th>Pilihan</th>
<th v-for="(option, keys) in columns" :key="keys + 'A'">
{{ option.value }}
</th>
</tr>
<tr v-for="(option, keys) in rows" :key="keys + 'A'">
<th>
{{ option.value }}
</th>
<td v-for="(option, key) in columns" :key="key + 'B'">
<v-radio-group
v-model="answer"
#change="update"
:rules="answerRule"
>
<v-radio
solo
:key="key"
:value="option.value"
>
</v-radio>
</v-radio-group>
</td>
</tr>
</thead>
<tbody></tbody>
</v-radio-group>
</template>
Here is my script on how to load the data and try to save the json:
<script>
export default {
props: ['question'],
data() {
return {
rows: this.question.options,
answer: [],
columns: this.question.optionsColumns,
answerRule: [],
}
},
methods: {
async update() {
try {
let payload = {
questionId: this.question.id,
value: this.answer,
questionName: this.question.question,
}
//update question options
await this.$store.commit('answers/update', payload)
} catch (err) {
this.$store.commit('alerts/show', {
type: 'error',
message: err.response
? this.$t(err.response.data.message)
: this.$t('SERVER_ERROR'),
})
}
},
},
beforeMount() {
if (this.question.required) {
this.answerRule.push(
(v) => v.length > 0 || this.$t('QUESTION_REQUIRED')
)
}
},
}
</script>
I am creating a vuetify simple table that is going to display various data elements. The problem is, some of those elements are based on relationships and nested. Getting the top level data is fine, and if I pull the nested data as a standalone, it works fine as well.
However, what I want to do is utilize an array to avoid repetitive html code for the table. Is this possible at all?
Below is the code as constructed for the table itself.
HTML:
<v-simple-table fixed-header height="300px">
<template v-slot:default>
<thead>
<tr>
<th class="text-left">
Attribute
</th>
<th class="text-left">
Value
</th>
</tr>
</thead>
<tbody>
<tr
v-for="(serviceProperty, idx) in serviceProperties"
:key="idx">
<th>{{ serviceProperty.label }}</th>
<td>{{ service[serviceProperty.value] }}</td>
</tr>
</tbody>
</template>
</v-simple-table>
JS:
export default {
name: "Details",
data() {
return {
loading: true,
service: {},
serviceProperties: [
{
label: 'Description',
value: 'description'
},
{
label: 'Location',
value: 'organization.locations[1].streetAddress'
},
{
label: 'EIN',
value: 'organization.EIN'
}
]
};
},
props: ["serviceId"],
async created() {
this.service = await Vue.$serviceService.findOne(this.serviceId);
this.loading = false;
},
};
This seems unnecessarily complicated.
Consider using computed, like this
...
computed: {
mappedData() {
return this.service.map(item => {
Description: item.Description,
Location: item.organization.locations[1].streetAddress,
EIN: item.organization.EIN
})
}
}
...
You can then access the data in the template with:
...
<element v-for="item in mappedData">
{{item.Description}}
{{item.Location}}
{{item.EIN}}
</element>
...
What i would like to do is manipulate the built-in html input buttons for increment and decrement of numbers. If there is a "vue-way" of doing this, that would of course be preferred.
First of all i'm working on a small vue-app that i've created for learning Vue, what i got now is a Vuex store which contains the state and methods for a shopping cart. I have bound the value item.itemCount seen in the image, to the value of the inputfield. But i would like the increment/decrement buttons to actually update the vuex-state in a proper way.
<input
class="slim"
type="number"
v-model.number="item.itemCount"
/>
I understand that i can just stop using a input-field, and create my own "count-view" + two buttons, but i'm curious if it's possible to do something like this.
UPDATE
Shoppingcart.vue
<template>
<div class="sliding-panel">
<span class="header">Shopping Cart</span>
<table>
<thead>
<th>Item Name</th>
<th>Count</th>
<th>Remove</th>
</thead>
<transition-group name="fade">
<tr v-for="item in items" :key="item.id">
<td>{{ item.name }}</td>
<td>
<input class="slim" type="number" v-model.number="item.itemCount" />
</td>
<td><button #click="removeProductFromCart(item)">Remove</button></td>
</tr>
</transition-group>
<tr>
Current sum:
{{
sum
}}
of
{{
count
}}
products.
</tr>
</table>
</div>
</template>
<script>
import { mapState, mapActions } from "vuex";
export default {
computed: mapState({
items: (state) => state.cart.items,
count: (state) => state.cart.count,
sum: (state) => state.cart.sum,
}),
methods: mapActions("cart", ["removeProductFromCart"]),
};
</script>
<style>
</style>
First you don't need to "overwrite increment/decrement handling" in any way. You have the <input> so you need to handle all user inputs changing value - be it inc/dec buttons or user typing value directly...
Proper way of updating Vuex state is by using mutations. So even it's technically possible to bind v-model to some property of object stored in Vuex (as you do), it's not correct "Vuex way"
If there is only single value, you can use computed prop like this:
computed: {
myValue: {
get() { return this.$store.state.myValue },
set(value) { this.$store.commit('changemyvalue', value )} // "changemyvalue" is defined mutation in the store
}
}
...and bind it to input
<input type="number" v-model="myValue" />
But because you are working with array of values, it is more practical to skip v-model entirely - in the end v-model is just syntactic sugar for :value="myValue" #input="myValue = $event.target.value"
In this case
<input type="number" :value="item.itemCount" min="1" #input="setItemCount({ id: item.id, count: $event.target.value})"/>
...where setItemCount is mutation created to change item count in the cart
Working example:
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
items: [
{ id: 1, name: 'Socks', itemCount: 2},
{ id: 2, name: 'Trousers', itemCount: 1}
]
},
mutations: {
setItemCount(state, { id, count }) {
const index = state.items.findIndex((item) => item.id === id);
if(index > -1) {
const item = state.items[index]
item.itemCount = count;
console.log(`Changing count of item '${item.name}' to ${count}`)
}
}
}
})
const app = new Vue({
store,
template: `
<div>
<span>Shopping Cart</span>
<table>
<thead>
<th>Item Name</th>
<th>Count</th>
<th>Remove</th>
</thead>
<transition-group name="fade">
<tr v-for="item in items" :key="item.id">
<td>{{ item.name }}</td>
<td>
<input type="number" :value="item.itemCount" min="1" #input="setItemCount({ id: item.id, count: $event.target.value})"/>
</td>
<td><button>Remove</button></td>
</tr>
</transition-group>
</table>
</div>
`,
computed: {
...Vuex.mapState({
items: (state) => state.items,
})
},
methods: {
...Vuex.mapMutations(['setItemCount'])
}
})
app.$mount("#app")
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.12/vue.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vuex/3.5.1/vuex.min.js"></script>
<div id="app"> </div>
I'm making a Anuglar2 application for people to log how many hours they put into each course, assignments, etc., per week (though there we be more advance options later on).
Right now i have a table which lists out how many hours you spent on each course per day. I want the user to be able to just edit and change any values as he/she goes along. So i have a two dimensional array ( named data), and i attach models to each element in the array, which i then represent as a input element.
Everything works fine, but there is a weird bug. Whenever you delete the value in the input box and re-enter new data, it jumps to the next input element. I cant figure out why. Anyone got any ideas ?
Example in GIF format (sorry for the quality had to use a converter)
gif link in case you cant see it on Stack
home.html
<!-- Table -->
<div class="row">
<div class="col-lg-12 col-sm-12">
<h1 class="page-header">Weekly Status Report</h1>
<table class="table table-responsive table-stripped table-bordered table-hover" *ngIf="courses">
<thead>
<tr class="btn-primary">
<th>Course</th>
<th>Time</th>
<th>SM #</th>
<th>Est</th>
<th *ngFor="let weekday of week">
{{weekday | date:'EEEE'}}
</th>
<th>Total</th>
</tr>
</thead>
<tbody *ngFor="let course of courses; let i = index;">
<tr>
<td >
{{course.name}}
</td>
</tr>
<tr class="alert-info">
<!-- Account for the title row -->
<td>
Date
</td>
<td >
Documentation Type
</td>
<td>
Documentation Text
</td>
</tr>
<tr *ngFor="let content of course.hours" class="alert-warning">
<td>
{{content.day| date}}
</td>
<td [attr.colspan]="3">
{{ title }}
</td>
<td [attr.colspan]="7">
</td>
</tr>
<tr class="alert-success">
<td></td>
<td></td>
<td></td>
<th></th>
<!-- DATA ARRAY -->
<th *ngFor="let d of data[i]; let j = index;">
<div>
<input maxlength="3" size="3" [(ngModel)]="data[i][j]" />
</div>
</th>
<td></td>
</tr>
</tbody>
<tfoot class="btn-primary">
<tr>
<td>Report Totals(all courses)</td>
<td></td>
<td></td>
<td></td>
<td *ngFor="let pivot of [0,1,2,3,4,5,6]">
{{ getSum(pivot) }}
</td>
<td>
{{getTotal()}}
</td>
</tr>
</tfoot>
</table>
</div>
</div>
home.component.ts
week: Array<any> = new Array();
data: Array<any> = new Array();
constructor(private hm: HomeService) {
let subscription = this.hm.getFormat(this.courses, this.week)
.subscribe(
value => {
this.data.push(value);
},
error => {
console.log(error)
},
() => {
console.log("Formated");
}
);
}
home.service.ts
getFormat(courses: any, weekdays: any): Observable<any> {
return new Observable(observer => {
// For all courses
courses.forEach(c => {
// temp week
let week: Array<any> = new Array();
// For each weekday
weekdays.forEach(w => {
let found: boolean = false;
// get hours spent on course
c.hours.forEach(h => {
let hour:Date = new Date (h.day);
// if the hours spent match up on the day push it to the week array
if (w.day.getTime() === hour.getTime()) {
week.push(h.duration);
found = true
}
});
// If no time was found on this take, push a empty string.
if (!found) {
week.push(0);
}
});
// push that week to the component
observer.next(week);
});
observer.complete();
});
}
This is happening because of how data is tracked.
When you change the value from the array it will become another value, thus not being able to track it as it will keep track of the older value.
Your case is similar to the following bad code:
#Component({
selector: 'my-app',
template: `
<div>
<table>
<tr *ngFor="let dim1 of values; let dim1Index = index">
<td *ngFor="let dim2 of dim1; let dim2Index = index">
<input type="text" [(ngModel)]="values[dim1Index][dim2Index]" />
</td>
</tr>
</table>
</div>
`,
})
export class App {
values: string[][];
constructor() {
this.values = [
['a1', 'b1', 'c1'],
['a2', 'b2', 'c2'],
['a3', 'b3', 'c3']
];
}
}
There are multiple solutions:
Solution 1: Using an object to wrap the value
Look at the values array.
#Component({
selector: 'my-app',
template: `
<div>
<table>
<tr *ngFor="let dim1 of values; let dim1Index = index">
<td *ngFor="let dim2 of dim1; let dim2Index = index">
<input type="text" [(ngModel)]="values[dim1Index][dim2Index].value" />
</td>
</tr>
</table>
<br/>
{{ values | json }}
</div>
`,
})
export class App {
values: string[][];
constructor() {
this.values = [
[{ value: 'a1' }, { value: 'b1' }, { value: 'c1' }],
[{ value: 'a2' }, { value: 'b2' }, { value: 'c2' }],
[{ value: 'a3' }, { value: 'b3' }, { value: 'c3' }]
];
}
}
Solution 2: Using a custom trackBy function for *ngFor
Note that this solution is based on trackByIndex function which returns the index of the item, thus the item being located by its index instead of its value.
#Component({
selector: 'my-app',
template: `
<div>
<table>
<tr *ngFor="let dim1 of values; let dim1Index = index; trackBy: trackByIndex">
<td *ngFor="let dim2 of dim1; let dim2Index = index; trackBy: trackByIndex">
<input type="text" [(ngModel)]="values[dim1Index][dim2Index]" />
</td>
</tr>
</table>
<br/>
{{ values | json }}
</div>
`,
})
export class App {
values: string[][];
constructor() {
this.values = [
['a1', 'b1', 'c1'],
['a2', 'b2', 'c2'],
['a3', 'b3', 'c3']
];
}
public trackByIndex(index: number, item) {
return index;
}
}
Therefore in your code you can use:
<tbody *ngFor="let course of courses; let i = index; trackBy: trackByIndex">
next
<th *ngFor="let d of data[i]; let j = index; trackBy: trackByIndex">
and finally define trackByIndex in your component:
public trackByIndex(index: number, item) {
return index;
}
I have a form to insert data to a table. When i delete data from table , the data is removed but the table row is not deleted.
It appears that the data is two way binding so data is removed but the html structure remains same.
Component
export class HomeComponent implements OnInit {
studentform = new FormGroup({
id: new FormControl(),
name: new FormControl(),
address: new FormControl()
});
student: Student[]=[];
std: Student= new Student();
constructor(public homeService: HomeService){ }
OnInit(){
this.getData();
}
getData(){
this.student = this.homeService.GetData();
}
onEdit(id:number){
console.log("Edit:" + id);
}
onDelete(id:number){
this.homeService.delete(id);
this.getData();
}
Save(model:Student){
this.homeService.SaveData(model);
this.studentform.reset();
this.getData();
}
}
Service
#Injectable()
export class HomeService{
student:Student[]=[];
SaveData(model:Student){
this.student.push(model);
}
GetData(){
return this.student;
}
delete(id:number){
for(var i=0;i<this.student.length;i++){
if(this.student[i].id==id){
delete this.student[i]
}
}
}
}
Template
div class="col-md-6">
<h5> Lists </h5>
<table>
<th>ID </th>
<th>Name </th>
<th>Address </th>
<th>Edit </th>
<th>Delete </th>
<tr *ngFor="let x of student">
<td> {{ x.id }} </td>
<td> {{ x.name }} </td>
<td> {{ x.address }} </td>
<td (click)="onEdit(x.id)"> Edit </td>
<td (click)="onDelete(x.id)"> Delete </td>
</tr>
</table>
Help me update the html (template) when data changes.
This is the result after I click table : data is gone but row remains
You are actually deleting the object but it's reference remain in the primary array. Try this instead :
delete(id:number){
for(var i=0;i<this.student.length;i++){
if(this.student[i].id==id){
this.student.splice(i, 1); //delete this.student[i]
break;
}
}
}
delete this.student[i] is not the correct way to remove an element from an array in this situation. You need to use splice().
this.student.splice(i, 1);
Also you should do a truthy check when displaying object fields in the template. Otherwise you will get errors like that. Usually safe-navigation operator(?) will do the trick.
Example:
<td> {{ x?.id }} </td>