I want to show the total amount from the data, but how can I do it with vue js in the simplest way?
There is a field where I need to write the sum of the balance amounts, but I cannot do much because the room is outside the for.
const app = new Vue({
el: '#app',
data: {
userList: [{
id: 1,
name: "Prem",
gender: "male",
balance:'3522'
},
{
id: 2,
name: "Chandu",
gender: "female",
balance:'2762'
},
{
id: 3,
name: "Jong",
gender: "female",
balance:'2000'
},
{
id: 4,
name: "Steew",
gender: "male",
balance:'2000'
},
{
id: 5,
name: "Abdollah",
gender: "female",
balance:'2000'
},
{
id: 6,
name: "Jerry",
gender: "male",
balance:'1500.5'
}
]
}
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.js"></script>
<script src="https://unpkg.com/vue-router#2.0.0/dist/vue-router.js"></script>
<div id="app">
<table class="table table-hover table-striped table-bordered">
<thead>
<tr>
<th>Name</th>
<th>Gender</th>
<th>Pice</th>
</tr>
</thead>
<tbody>
<tr v-for="(user, i) in userList" class="position-relative">
<td>{{ user.name }}</td>
<td>{{ user.gender }}</td>
<td>{{user.balance}}<td>
</tr>
</tbody>
<tfoot>
<tr>
<td>total number of records: {{userList.length}}</td>
<td></td>
<td>Total:</td>
</tr>
</tfoot>
</table>
</div>
Define total as a computed property using reduce function as follows :
data: {
userList: [...],
},
computed:{
total(){
return this.userList.reduce((acc,curr)=>{
return acc+=(+curr)
},0)
}
}
}
in template :
<td>Total: {{total}}</td>
Related
Can someone tell me how to write an array of objects in Vuex
I will explain the essence
In this situation, I need to create an order management system
I have an array of products with different data
This array I get from the server using axios request
Via v-for, I displayed this array in the select option html tag
Next, by clicking on the html option tag, I need to add the product to the data table
Also, with the addition of a specific product to the table, it is necessary that the product for which a click is made is recorded in the Vuex store, but not with rewriting, but with addition to existing data
Next, in synchronization with the addition to the Vuex store, information is output from the Vuex store to the table
this is my code in Vue Component
<div class="row">
<div class="col-md-8">
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>Name</th>
<th>Price</th>
<th>QTY</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
</div>
<div class="col-md-4">
<form>
<div class="form-group">
<label for="products">Select Products</label>
<select v-model="orderData" #change="addOrderData" id="products" class="form-control">
<option v-for="product in products" multiple v-bind:value="{productId: product.id, name: product.name, price: product.price}">{{product.name}}</option>
</select>
<pre>{{orderData}}</pre>
</div>
</form>
</div>
</div>
data() {
return {
selected: '',
formData: {
userId: ''
},
orderData: {
productId: [],
price: [],
total: [],
quantity: []
}
}
},
methods: {
addOrderData()
{
let data = {
productId: this.orderData.productId,
name: this.orderData.name,
price: this.orderData.price,
}
this.$store.commit('orders/setOrderProduct', data)
}
},
this is my code in Vuex store
function initialState () {
const orderProducts = [];
return {
orderProducts
}}
const getters = {
orderProducts(state)
{
return state.orderProduct;
},};
const mutations = {
setOrderProduct(state, orderProduct)
{
state.orderProduct = orderProduct;
}};
If I understand you correctly, please check the following:
template:
<select v-model="orderData" #change="addOrderData">
<option v-for="(product) in products" :key="product.productId" :value="{productId: product.productId, name: product.name, price: product.price}">
{{product.productId}} - {{product.name}}</option>
</select>
<br /><br />
<table>
<thead>
<tr>
<th>name</th>
<th>price</th>
</tr>
</thead>
<tbody v-if="orderProducts.length > 0">
<tr v-for="(item, index) in orderProducts" :key="index">
<td>{{item.name}}</td>
<td>{{item.price}}</td>
</tr>
</tbody>
<tbody v-else>
<tr>
<td colspan="2">No products to display</td>
</tr>
</tbody>
</table>
code:
Vue.use(Vuex);
const store = new Vuex.Store({
state: {
orderProducts: []
},
mutations: {
addProduct(state, payload) {
state.orderProducts.push(payload);
}
}
})
new Vue({
store,
el: '#app',
data() {
return {
products: [{
productId: 1,
name: 'Product One',
price: 10
},
{
productId: 2,
name: 'Product Two',
price: 15
}
],
orderData: {
productId: [],
price: [],
total: [],
quantity: []
}
};
},
computed: {
orderProducts() {
return this.$store.state.orderProducts;
}
},
methods: {
addOrderData() {
this.$store.commit('addProduct', this.orderData);
}
}
});
The idea is when change event is triggered by selecting an option, you commit mutation to the store with the selected product as payload. The orderProducts computed property will refresh, and the table will get the latest data. You can check this jsfiddle.
Guys I'm starting with Vue and I'm having a little difficulty. In the image below I have a table with some items and when I will increase the amount of the item Orange for example is increased all other items, how to fix it?
enter image description here
My code
new Vue({
el: '#app',
data() {
return {
quantity: 1,
fruits: [
{ Code: 1, Name: 'Abacaxi', Price: "50.00" },
{ Code: 2, Name: 'Abacate', Price: "50.00" },
{ Code: 3, Name: 'Morango', Price: "60.00" },
{ Code: 4, Name: 'Maçã', Price: "17.00" },
{ Code: 5, Name: 'Laranja', Price: "30.00" }
]
}
},
methods: {
add() {
this.quantity++
},
remove() {
if(this.quantity === 0) {
this.quantity = 0
} else {
this.quantity--
}
}
}
})
<script src="https://unpkg.com/vue"></script>
<div id="app">
<template>
<div class="user-list">
<table>
<thead>
<tr>
<th>#Code</th>
<th>Name</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr v-for="fruit in fruits" :key="fruit.Code">
<td>
<button #click="remove">-</button>
<input type="text" :value="quantity">
<button #click="add">+</button>
</td>
<td>{{ fruit.Name }}</td>
<td>{{ fruit.Price }}</td>
</tr>
</tbody>
</table>
</div>
</template>
</div>
You should just need to have a quantity on each item in your list. You'd then pass the relevant item to add or remove.
new Vue({
el: '#app',
data() {
return {
fruits: [
{ Code: 1, Name: 'Abacaxi', Price: "50.00", quantity: 1 },
{ Code: 2, Name: 'Abacate', Price: "50.00", quantity: 1 },
{ Code: 3, Name: 'Morango', Price: "60.00", quantity: 1 },
{ Code: 4, Name: 'Maçã', Price: "17.00", quantity: 1 },
{ Code: 5, Name: 'Laranja', Price: "30.00", quantity: 1 }
]
}
},
methods: {
add(fruit) {
fruit.quantity++
},
remove(fruit) {
if(fruit.quantity !== 0) {
fruit.quantity--
}
}
}
})
<script src="https://unpkg.com/vue#2.6.10/dist/vue.js"></script>
<div id="app">
<template>
<div class="user-list">
<table>
<thead>
<tr>
<th>#Code</th>
<th>Name</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr v-for="fruit in fruits" :key="fruit.Code">
<td>
<button #click="remove(fruit)">-</button>
<input type="text" v-model.number="fruit.quantity">
<button #click="add(fruit)">+</button>
</td>
<td>{{ fruit.Name }}</td>
<td>{{ fruit.Price }}</td>
</tr>
</tbody>
</table>
</div>
</template>
</div>
I've also switched :value to v-model.number, which seems more likely to be what you'd want though it's not directly related to the problem mentioned in the question.
I am trying to select checkboxes based on some condition.
Select all checkboxes (select all checkboxes)
select all unread (select all unread where data array has status of
unread)
select all read (select all read where data array has status of read)
I am able to select all checkboxes on checkbox click,but unable to select it with links
I also need to fetch the ids of selected checkboxes,so i can perform action against these selected checkboxes.
Can you guys please have a look at this.
new Vue({
el: "#app",
data: {
selected: [],
messages: [{
id: 1,
text: "Learn JavaScript",
status: 'read'
},
{
id: 2,
text: "Learn Vue",
status: 'unread'
},
{
id: 3,
text: "Play around in JSFiddle",
status: 'read'
},
{
id: 4,
text: "Build something awesome",
status: 'unread'
}
]
},
methods: {
},
computed: {
selectAll: {
get: function() {
return this.messages ? this.selected.length == this.messages.length : false;
},
set: function(value) {
var selected = [];
if (value) {
this.messages.forEach(function(item) {
selected.push(item.id);
});
}
this.selected = selected;
}
}
},
})
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#app {
background: #fff;
border-radius: 4px;
padding: 20px;
transition: all 0.2s;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/vue#2.5.16/dist/vue.js"></script>
<div id="app">
<h2>Message App:</h2>
<table class="table">
All,
Read,
Unread,
<thead>
<tr>
<th><input type="checkbox" v-model="selectAll"></th>
<th>Status</th>
<th>Message</th>
</tr>
</thead>
<tbody>
<tr v-for="(item,index) in messages">
<td><input type="checkbox" v-model="selected" :value="item.id"></td>
<td>{{ item.status }}</td>
<td>{{ item.text }}</td>
</tr>
</tbody>
</table>
</div>
You might want to use click event on a element:
All,
and in javascript code:
methods: {
selectAllHandler() {
if (this.selected.length) {
this.selected = []
} else {
this.selected = this.messages.map(item => item.id);
}
}
}
Your Javascript:
new Vue({
el: "#app",
data: {
selected: [],
messages: [{
id: 1,
text: "Learn JavaScript",
status: 'read'
},
{
id: 2,
text: "Learn Vue",
status: 'unread'
},
{
id: 3,
text: "Play around in JSFiddle",
status: 'read'
},
{
id: 4,
text: "Build something awesome",
status: 'unread'
}
]
},
methods: {
selectAll() {
this.selected = this.messages.map((message) => message.id);
}
}
})
Your HTML:
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/vue#2.5.16/dist/vue.js"></script>
<div id="app">
<h2>Message App:</h2>
<table class="table">
All,
Read,
Unread,
<thead>
<tr>
<th><input type="checkbox" v-model="selectAll"></th>
<th>Status</th>
<th>Message</th>
</tr>
</thead>
<tbody>
<tr v-for="(item,index) in messages">
<td><input type="checkbox" v-model="selected" :value="item.id"></td>
<td>{{ item.status }}</td>
<td>{{ item.text }}</td>
</tr>
</tbody>
I've copied my current code below. I'm trying to dynamically generate table headers depending on what type I pass as a prop to my tables component (standings and status are what I have as the data arrays in my example).
I've accomplished this by using the if statement in the header computed value to return the proper list.
However I'd like to not have to add additional if statements for every type.
Is there a way that I can leverage the type prop to bind directly to the matching data?
<div id="root" class="container">
<tables type="stats">
</tables>
</div>
Vue.component('tables', {
template: `
<table class="table">
<thead>
<tr>
<th v-for="headers in header">{{ headers }}</th>
</tr>
</thead>
<tfoot>
<tr>
<th v-for="footers in header">{{ footers }}</th>
</tr>
</tfoot>
<tbody>
<tr>
<th>1</th>
<td>Leicester City <strong>(C)</strong>
<slot></slot>
</tr>
</tbody>
</table>
`,
data () {
return {
standings: ['Rank', 'Team', 'Wins', 'Losses'],
stats: ['Number', 'Player', 'Position', 'RBI', 'HR']
};
},
computed: {
header() {
if (this.type == 'standings') {
return this.standings;
} else {
return this.stats;
}
}
},
props: {
type: { required: true }
}
});
If you change up your data structure slightly, you can remove your if statements.
data () {
return {
types:{
standings: ['Rank', 'Team', 'Wins', 'Losses'],
stats: ['Number', 'Player', 'Position', 'RBI', 'HR']
}
};
},
computed: {
header() {
return this.types[this.type]
}
},
props: {
type: { required: true }
}
Here is an example.
Vue.component('tables', {
template: `
<table class="table">
<thead>
<tr>
<th v-for="headers in header">{{ headers }}</th>
</tr>
</thead>
<tfoot>
<tr>
<th v-for="footers in header">{{ footers }}</th>
</tr>
</tfoot>
<tbody>
<tr>
<th>1</th>
<td>Leicester City <strong>(C)</strong>
<slot></slot>
</td>
</tr>
</tbody>
</table>
`,
data () {
return {
types:{
standings: ['Rank', 'Team', 'Wins', 'Losses'],
stats: ['Number', 'Player', 'Position', 'RBI', 'HR']
}
};
},
computed: {
header() {
return this.types[this.type]
}
},
props: {
type: { required: true }
}
});
new Vue({
el: "#root"
})
<script src="https://unpkg.com/vue#2.2.6/dist/vue.js"></script>
<div id="root" class="container">
<tables type="stats">
</tables>
</div>
How can I filter by searching in multiple search keys?
I'm trying something like this, but (of course) it won't work:
<tr v-repeat="questions | filterBy search in 'reference','user.name','shop.shopName'">
The filterBy custom filter is not documented AFAIK, but you can use a method to make your own filter:
var demo = new Vue({
el: '#demo',
data: {
search: 're',
people: [
{name: 'Koos', age: 30, eyes:'red'},
{name: 'Gert', age: 20, eyes:'blue'},
{name: 'Pieter', age: 12, eyes:'green'},
{name: 'Dawid', age: 67, eyes:'dark green'},
{name: 'Johan', age: 15, eyes:'purple'},
{name: 'Hans', age: 12, eyes:'pink'}
]
},
methods: {
customFilter: function(person) {
return person.name.indexOf(this.search) != -1
|| person.eyes.indexOf(this.search) != -1
;
}
},
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.26/vue.min.js"></script>
<div id="demo">
<input type="text" class="form-control" v-model="search"/>
<br/>
<table class="table">
<thead>
<tr>
<th>name</th>
<th>eyes</th>
<th>age</th>
</tr>
</thead>
<tr v-for="person in people | filterBy customFilter">
<td>{{ person.name }}</td>
<td>{{ person.eyes }}</td>
<td>{{ person.age }}</td>
</tr>
</table>
</div>
This problem resolve with "Computed Properties":
var app = new Vue({
el: '#demo',
data: {
search: '',
people: [
{name: 'Koos', age: 30, eyes:'red'},
{name: 'Gert', age: 20, eyes:'blue'},
{name: 'Pieter', age: 12, eyes:'green'},
{name: 'Dawid', age: 67, eyes:'dark green'},
{name: 'Johan', age: 15, eyes:'purple'},
{name: 'Hans', age: 12, eyes:'pink'}
]
},
computed: {
filteredPerson: function () {
var self = this;
return this.people.filter(function (person) {
return person.name.toLowerCase().indexOf(self.search.toLowerCase()) >= 0
|| person.eyes.toLowerCase().indexOf(self.search.toLowerCase()) >= 0;
});
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.min.js"></script>
<div id="demo">
<input type="text" class="form-control" v-model="search"/>
<br/>
<table class="table">
<thead>
<tr>
<th>name</th>
<th>eyes</th>
<th>age</th>
</tr>
</thead>
<tr v-for="person in filteredPerson">
<td>{{ person.name }}</td>
<td>{{ person.eyes }}</td>
<td>{{ person.age }}</td>
</tr>
</table>
</div>
Since Vue.js version 0.12.11 this is possible with:
<li v-repeat="user in users | filterBy searchText in 'name' 'phone'"></li>
Make sure to checkout the official guide on this: http://vuejs.org/api/#orderBy
computed: {
filteredItems() {
var result = this.accountList;
if (this.flt.userName != undefined) {
result = result.filter(
item =>
item.userName.toLowerCase().includes(
this.flt.userName.toLowerCase()
)
);
}
if (this.flt.tenantId != undefined) {
result = result.filter(
item =>
item.tenantId.includes(
this.flt.tenantId
)
);
}
if (this.flt.providerId != undefined) {
result = result.filter(
item =>
item.providerId.includes(
this.flt.providerId
)
);
}
return result;
}
},