I have dynamic products list to create an invoice. Now I want to search the product from select->option list. I found a possible solution like Vue-select in vuejs but I could not understand how to convert my existing code to get benefit from Vue-select. Would someone help me please, how should I write code in 'select' such that I can search product at a time from the list?
My existing code is -
<td>
<select id="orderproductId" ref="selectOrderProduct" class="form-control input-sm" #change="setOrderProducts($event)">
<option>Choose Product ...</option>
<option :value="product.id + '_' + product.product_name" v-for="product in invProducts">#{{ product.product_name }}</option>
</select>
</td>
And I want to convert it something like -
<v-select :options="options"></v-select>
So that, I can search products also if I have many products. And My script file is -
<script>
Vue.component('v-select', VueSelect.VueSelect);
var app = new Vue({
el: '#poOrder',
data: {
orderEntry: {
id: 1,
product_name: '',
quantity: 1,
price: 0,
total: 0,
},
orderDetail: [],
grandTotal: 0,
invProducts: [],
invProducts: [
#foreach ($productRecords as $invProduct)
{
id:{{ $invProduct['id'] }},
product_name:'{{ $invProduct['product_name'] }}',
},
#endforeach
],
},
methods: {
setOrderProducts: function(event) {
//alert('fired');
var self = this;
var valueArr = event.target.value.split('_');
var selectProductId = valueArr[0];
var selectProductName = valueArr[1];
self.orderEntry.id = selectProductId;
self.orderEntry.product_name = selectProductName;
$('#invQuantity').select();
},
addMoreOrderFields:function(orderEntry) {
var self = this;
if(orderEntry.product_name && orderEntry.quantity && orderEntry.price > 0) {
self.orderDetail.push({
id: orderEntry.id,
product_name: orderEntry.product_name,
quantity: orderEntry.quantity,
price: orderEntry.price,
total: orderEntry.total,
});
self.orderEntry = {
id: 1,
product_name:'',
productId: 0,
quantity: 1,
price: 0,
total: 0,
}
$('#orderproductId').focus();
self.calculateGrandTotal();
} else {
$('#warningModal').modal();
}
this.$refs.selectOrderProduct.focus();
},
removeOrderField:function(removeOrderDetail) {
var self = this;
var index = self.orderDetail.indexOf(removeOrderDetail);
self.orderDetail.splice(index, 1);
self.calculateGrandTotal();
},
calculateGrandTotal:function() {
var self = this;
self.grandTotal = 0;
self.totalPrice = 0;
self.totalQuantity = 0;
self.orderDetail.map(function(order){
self.totalQuantity += parseInt(order.quantity);
self.totalPrice += parseInt(order.price);
self.grandTotal += parseInt(order.total);
});
},
setTotalPrice:function(event){
var self = this;
//self.netTotalPrice();
self.netTotalPrice;
}
},
computed: {
netTotalPrice: function(){
var self = this;
var netTotalPriceValue = self.orderEntry.quantity * self.orderEntry.price;
var netTotalPriceInDecimal = netTotalPriceValue.toFixed(2);
self.orderEntry.total = netTotalPriceInDecimal;
return netTotalPriceInDecimal;
}
}
});
Assuming that invProducts is an array of product objects and each product object has a product_name property, try this snippet.
<v-select #input="selectChange()" :label="product_name" :options="invProducts" v-model="selectedProduct">
</v-select>
Create a new data property called selectedProduct and bind it to the vue-select component. So, whenever the selection in the vue-select changes, the value of selectedProduct also changes. In addition to this, #input event can be used to trigger a method in your component. You can get the selected product in that method and do further actions within that event listener.
methods: {
selectChange : function(){
console.log(this.selectedProduct);
//do futher processing
}
Related
Hello I am using data table and as per some business logic certain columns in my table are shown or hidden for that I am sending the aoColumns as JSon from Java side, but the problem I am facing is in rowCallBack functions
I am manipulating columns on indexes which is miss-matched when I hide columns
This is how I am manipulating columns:
$('td:eq(0)', nRow).html(""+nameTrimmed+ "");
my guess is hidden columns are not counted in the index and rowCallBack just manipulates any column that is visible on that index
I can not write different rowCallBack for every case to keep it generic
Is there any way I can include the hidden column in index count?
or may be modify columns in some other way apart from indexes.
Here is the code
$('#myTable').DataTable({
"dom": 't<"pagecontrol"lip>',
"bJQueryUI": true,
"sPaginationType": "simple",
"bServerSide": true,
"sAjaxSource": "${ctx}/getData?",
"bProcessing": true,
"oLanguage":
{
"sInfo": "<fmt:message key="DataTable.key.DT_SHOWING_ENTRIES" />",
"sInfoEmpty": "<fmt:message key="DataTable.key.DT_SHOWING_ENTRIES_EMPTY" />",
"oPaginate":
{
"sNext": '<i class="fa fa-caret-right"></i>',
"sLast": '<<',
"sFirst": '>>',
"sPrevious": '<i class="fa fa-caret-left"></i>'
}
},
"lengthMenu": [[50, 100, 150, 200], [50, 100, 150, 200]],
"rowCallback": function( nRow, dtoObj, iDisplayIndex, iDisplayIndexFull ) {
if (dtoObj.firstName != '' && !showDownloadButton) {
$("#participantDownloadButton").removeClass('hide');
showDownloadButton = true;
}
if(searchStringCount == dtoObj.searchStringCounter || dtoObj.searchStringCounter == 0) {
var name = dtoObj.firstName +" "+ dtoObj.lastName;
var nameTrimmed = trimStringByCharacters(name, 25);
$('td:eq(0)', nRow).html("<label title='"+name.trim()+"'>"+nameTrimmed+ "</label>");
//column 2 email
if(dtoObj.email!='') {
var email = trimStringByCharacters(dtoObj.email,20) ;
$('td:eq(1)', nRow).html("<label title='" + email + "'>" + email + "</label>");
}else{
$('td:eq(1)', nRow).html("");
}
//column 3 List name
var listName = dtoObj.eligibilityListName;
var listNameTrimmed = "";
if(listName!=null) {
listNameTrimmed = trimStringByCharacters(listName, 20);
}
$('td:eq(2)', nRow).html("<label title='"+listName+"'>"+listNameTrimmed+ "</label>");
var packageLevel = dtoObj.packageLevel;
var packageLevelTrimmed = trimStringByCharacters(packageLevel, 15);
$('td:eq(3)', nRow).html("<label title='"+packageLevel+"' data-participant-id='"+dtoObj.userId+"'>"+packageLevelTrimmed+ "</label>");
var durationUnit ='<fmt:message key="reports.filter.months"/>';
if (dtoObj.packageDuration == 1) {
durationUnit = '<fmt:message key="reports.filter.month"/>';
}
$('td:eq(4)', nRow).html(dtoObj.packageDuration +" "+ durationUnit);
// Add icons before status
var status = dtoObj.status;
var iconLink = getIconLinkByStatus(status);
// Add icons ends
if(dtoObj.status != null) {
$('td:eq(6)', nRow).html(iconLink + dtoObj.status);
} else {
$('td:eq(6)', nRow).html("");
}
}
},
"drawCallback": function() {
$(".dataTables_wrapper").children(".pagecontrol").find("#participantsTable_length label").contents().eq(0).replaceWith('<fmt:message key="rows.per.page"/> ');
$("#participantsTable").find(".dataTables_empty").html('<fmt:message key="no.data.in.table"/>');
//Code to diaply participant details view
$('#participantsTable tbody tr').on('click',function () {
var $tds = $(this).find('td');
var userId = $tds.eq(2).find('label').attr("data-participant-id");;
var status = $tds.eq(5).text();
var listName = $tds.eq(1).text();
showParticipantDetails(userId, status, listName);
});
},
"aoColumns": columnData //coming from server side
});
Does defining variables inside of a computed property have any impact on the perfomance of Vue components?
Background: I built a table component which generates a HTML table generically from the passed data and has different filters per column, filter for the whole table, sort keys, etc., so I'm defining a lot of local variables inside the computed property.
Imagine having an array of objects:
let data = [
{ id: "y", a: 1, b: 2, c: 3 },
{ id: "z", a: 11, b: 22, c: 33 }
]
..which is used by a Vue component to display the data:
<template>
<div>
<input type="text" v-model="filterKey" />
</div>
<table>
<thead>
<tr>
<th>A</th>
<th>B</th>
<th>C</th>
</tr>
</thead>
<tbody>
<tr v-for="item in filteredData" :key="item.id">
<td v-for="(value, key) in item" :key="key">
{{ value }}
</td>
</tr>
</tbody>
</table>
</template>
The data gets filtered via input:
<script>
export default {
props: {
passedData: Array,
},
data() {
return {
filterKey: null,
};
},
computed: {
filteredData() {
// defining local scope variables
let data = this.passedData;
let filterKey = this.filterKey;
data = data.filter((e) => {
// filter by filterKey or this.filterKey
});
return data;
},
},
};
</script>
My question refers to let data = .. and let filterKey = .. as filteredData() gets triggered from any change of the filterKey (defined in data()) so the local variable gets updated too, although they're not "reactive" in a Vue way.
Is there any impact on the performance when defining local variables inside a computed property? Should you use the reactive variables from data() (e. g. this.filterKey) directly inside of the computed property?
The best way to test if something affects performance, is to actually test it.
According to my tests below, it is consistency more than 1000% slower to use this.passedData instead of adding a variable on top of the function. (869ms vs 29ms)
Make sure you run your benchmarks on the target browsers you write your application for the best results.
function time(name, cb) {
var t0 = performance.now();
const res = cb();
if(res !== 20000000) {
throw new Error('wrong result: ' + res);
}
var t1 = performance.now();
document.write("Call to "+name+" took " + (t1 - t0) + " milliseconds.<br>")
}
function withoutLocalVar() {
const vue = new Vue({
computed: {
hi() {
return 1;
},
hi2() {
return 1;
},
test() {
let sum = 0;
for(let i = 0; i < 10000000; i++) { // 10 000 000
sum += this.hi + this.hi2;
}
return sum;
},
}
})
return vue.test;
}
function withLocalVar() {
const vue = new Vue({
computed: {
hi() {
return 1;
},
hi2() {
return 1;
},
test() {
let sum = 0;
const hi = this.hi;
const hi2 = this.hi2;
for(let i = 0; i < 10000000; i++) { // 10 000 000
sum += hi + hi2;
}
return sum;
},
}
})
return vue.test;
}
function benchmark() {
const vue = new Vue({
computed: {
hi() {
return 1;
},
hi2() {
return 1;
},
test() {
let sum = 0;
const hi = 1;
const hi2 = 1;
for(let i = 0; i < 10000000; i++) { // 10 000 000
sum += hi + hi2;
}
return sum;
},
}
})
return vue.test;
}
time('withoutLocalVar - init', withoutLocalVar);
time('withLocalVar - init', withLocalVar);
time('benchmark - init', benchmark);
time('withoutLocalVar - run1', withoutLocalVar);
time('withLocalVar - run1', withLocalVar);
time('benchmark - run1', benchmark);
time('withoutLocalVar - run2', withoutLocalVar);
time('withLocalVar - run2', withLocalVar);
time('benchmark - run2', benchmark);
<script src="https://cdn.jsdelivr.net/npm/vue#2.5.17/dist/vue.js"></script>
temlate
<bm-offer-confirm inline-template>
<select v-model="selectedCard">
<option v-for="card in cards"
v-bind:value="card.id">#{{card.info}}</option>
</select>
</bm-offer-confirm>
in the component
module.exports = {
data() {
return {
selectedCard: 0,
cards: {},
}
}
created(){
Bus.$on('setCardsList', function (cards) {
self.cards = cards;
this.selectedCard = cards[0].id;
//alert(this.selectedCard) shows 2
});
}
if i set selectedCard: 2 in data() it's work correctly and option is selected, but in my example it does not work. selected value is empty(not checked), why? I can select option only manualuty.
How you fill the cards object ? Are you getting any exception in console ?
No, it's result of emited in other component
created() {
this.getCards();
},
methods: {
getCards() {
this.$http.get('/get-cards/')
.then(response => {
this.cards = response.data;
Bus.$emit('setCardsList', this.cards);
})
},
//The Bus is Vue object;
//window.Bus = new Vue();
omg, I fixed it
created(){
var self = this; //add self link
Bus.$on('setCardsList', function (cards) {
self.cards = cards;
self.selectedCard = cards[0].id; // before this.selectedCard = cards[0].id;
//alert(this.selectedCard) shows 2
});
}
Is there a way to disable the keyboard events on Kendo UI Slider? Basically, I want to prevent changing the value of the slider when pressing left and right arrow keys. Is this possible at all?
Please note that slider is being dynamically inserted into the DOM as part of a KO custom binding handler.
ko.bindingHandlers.tone = {
init: function(element, valueAccessor) {
if (valueAccessor().settingToneEnabled) {
var $el = $(element);
var tag = '<span class="dropdown mrgn-tp-md"><ul class="dropdown-menu dropdown-menu-right text-center pddng-sm" aria-labelledby="tonedropdownMenu"><li class="pddng-lft-md pddng-rght-sm"><span id="tone-slider" title="tone"></span></li><li class="pddng-rght-sm"><i class="icon icon-delete"></i> ' + i18n['ps-deleteArticleToneLabel'] + '</li></ul></span>';
$(tag).appendTo($el);
var $slider = $('#tone-slider', $el);
var $delLink = $('a.del', $el);
var $dropdown = $('span.dropdown', $el);
$('a.dropdown-toggle', $dropdown).on('click', function() {
$('.dropdown-menu', $dropdown).toggle();
});
$slider.kendoSlider({
change: function(e) {
var va = valueAccessor();
va.value(e.value);
if ($.isFunction(va.handleUserInput)) {
va.handleUserInput();
}
},
showButtons: false,
min: -1,
max: 1,
smallStep: 1,
value: valueAccessor().value() || 0,
tickPlacement: 'none',
tooltip: {
enabled: false
}
});
$('.k-draghandle', $el).off('keydown');
$delLink.on('click', function(e) {
e.preventDefault();
if ($delLink.attr('disabled')) {
return;
}
var va = valueAccessor();
va.value(null);
if ($.isFunction(va.handleUserInput)) {
va.handleUserInput();
}
});
$el.data('slider', $slider.data("kendoSlider"));
$el.data('deleteButton', $delLink);
$el.data('dropdown', $dropdown);
} else {
$('<span href="" data-tone></span>').appendTo(element);
}
},
update: function(element, valueAccessor) {
var toneValues = {
'1': {
name: i18n['ps-tonePositive'],
val: 1,
css: 'icon-tone-positive'
},
'0': {
name: i18n['ps-toneNeutral'],
val: 0,
css: 'icon-tone-neutral'
},
'-1': {
name: i18n['ps-toneNegative'],
val: 0,
css: 'icon-tone-negative'
},
};
var $tone = $('*[data-tone]', element);
var val = valueAccessor().value() || 0;
var tone = toneValues[val.toString()] || toneValues['0'];
$tone.removeClass()
.addClass('icon').addClass(tone.css)
.attr('title', tone.name);
if (valueAccessor().settingToneEnabled) {
$('#tone-slider', element).data("kendoSlider").value(val);
}
},
};
You can try to remove the keydown handler.
See demo.
I have a simple table (type sap.ui.table.Table) where I allow my users to sort, filter and group elements. However there is no possibility to remove sorting or grouping once it is applied? The filter could be removed by entering no value in the filter, but how do I remove sorting/grouping?
var oTableEmpl = new sap.ui.table.Table({
width : "100%",
visibleRowCount : 20,
selectionMode : sap.ui.table.SelectionMode.Multi,
navigationMode : sap.ui.table.NavigationMode.Scrollbar,
editable : false,
enableCellFilter : true,
enableColumnReordering : true,
enableGrouping : true,
extension : oMatrixLayout,
});
oTableEmpl.addColumn(new sap.ui.table.Column({
label : new sap.ui.commons.Label({
text : "Label",
textAlign : sap.ui.core.TextAlign.Center
}),
template : new sap.ui.commons.TextView({
text : "{Value}",
textAlign : sap.ui.core.TextAlign.Center
}),
visible : false,
sortProperty: "Value",
filterProperty: "Value",
}));
This might seem easy, but in the table itself there is no option to remove anything. Does it really have to be removed by programming something?
Yes, there is only way to do this by coding. Basically you need to clear sorters and filters of the ListBinding, and then refresh the DataModel. For grouping, reset the grouping of Table and Column to false, after reset, set grouping of Table back to true.
//set group of table and column to false
oTableEmpl.setEnableGrouping(false);
oTableEmpl.getColumns()[0].setGrouped(false);
var oListBinding = oTableEmpl.getBinding();
oListBinding.aSorters = null;
oListBinding.aFilters = null;
oTableEmpl.getModel().refresh(true);
//after reset, set the enableGrouping back to true
oTableEmpl.setEnableGrouping(true);
I also attached a working code snippet. Please have a check.
<script id='sap-ui-bootstrap' type='text/javascript' src='https://sapui5.hana.ondemand.com/resources/sap-ui-core.js' data-sap-ui-libs="sap.m,sap.ui.commons,sap.ui.table,sap.viz" data-sap-ui-theme="sap_bluecrystal"></script>
<script id="view1" type="sapui5/xmlview">
<mvc:View xmlns:core="sap.ui.core" xmlns:layout="sap.ui.commons.layout" xmlns:mvc="sap.ui.core.mvc" xmlns="sap.ui.commons" xmlns:table="sap.ui.table" controllerName="my.own.controller" xmlns:html="http://www.w3.org/1999/xhtml">
<layout:VerticalLayout>
<Button text="Reset" press="onPress" />
<table:Table id="testTable" rows="{/}" enableGrouping="true">
<table:Column sortProperty="abc" sorted="true" visible="true">
<table:label>
<Label text="abc"></Label>
</table:label>
<table:template>
<Label text="{abc}"></Label>
</table:template>
</table:Column>
<table:Column>
<table:label>
<Label text="abc2"></Label>
</table:label>
<table:template>
<Label text="{abc2}"></Label>
</table:template>
</table:Column>
</table:Table>
</layout:VerticalLayout>
</mvc:View>
</script>
<script>
sap.ui.controller("my.own.controller", {
onInit: function() {
var aTableData = [{
abc: 1,
abc2: "a"
}, {
abc: 6,
abc2: "b"
}, {
abc: 6,
abc2: "c"
}, {
abc: 3,
abc2: "g"
}, {
abc: 3,
abc2: "h"
}];
var oTableModel = new sap.ui.model.json.JSONModel();
oTableModel.setData(aTableData);
var oTable = this.getView().byId("testTable");
oTable.setModel(oTableModel);
oTable.sort(oTable.getColumns()[0]);
},
onPress: function() {
var oTable = this.getView().byId("testTable");
//set group of table and column to false
oTable.setEnableGrouping(false);
oTable.getColumns()[0].setGrouped(false);
var oModel = oTable.getModel();
var oListBinding = oTable.getBinding();
oListBinding.aSorters = null;
oListBinding.aFilters = null;
oModel.refresh(true);
//after reset, set the enableGroup back to true
oTable.setEnableGrouping(true);
}
});
var myView = sap.ui.xmlview("myView", {
viewContent: jQuery('#view1').html()
}); //
myView.placeAt('content');
</script>
<body class='sapUiBody'>
<div id='content'></div>
</body>
For openui5 v1.78.7: If you want to delete these Filters from the table:
You can do:
var columns = this.byId("tableId").getColumns();
for (var i = 0, l = columns.length; i < l; i++) {
var isFiltered = columns[i].getFiltered();
if (isFiltered) {
// clear column filter if the filter is set
columns[i].filter("");
}
}
You can clear sort filters with:
var columns = table.getColumns();
var sortedCols = table.getSortedColumns();
for (var i = 0, l = columns.length; i < l; i++) {
if (sortedCols.indexOf(columns[i]) < 0) {
columns[i].setSorted(false);
}
}
Make sure you set back sort on row binding if you had any with:
table.getBinding("rows").sort(new Sorter(sPath, bDescending));