I am creating a dynamic search bar that will filter a sidebar full of names based on user input. However, I am having trouble temporarily hiding and showing data based on the search bar's value on keyup. What is the best way to achieve this the "Vue way"?
On keyup, I want to filter through all of the this.people data and only show names that contain the value of the search input.
Below is what my code looks like
Vue.component('sidebar',{
props: ['people', 'tables'],
data: () => {
return {
fullName: ''
}
},
computed: {
computed() {
return [this.people, this.tables].join()
}
},
template:
`
<div id="sidebarContain" v-if="this.people">
<input id="sidebar-search" type="text" placeholder="Search..." #keydown="searchQuery">
<select id="sidebar-select" #change="sidebarChanged">
<option value="AZ">A-Z</option>
<option value="ZA">Z-A</option>
<option value="notAtTable">No Table</option>
<option value="Dean's Guest">Dean's Guest</option>
<option value="BOO | VIP">BOO | VIP</option>
</select>
<div v-for="person in people" :class="[{'checked-in': isCheckedIn(person)}, 'person']" :id="person.id" :style="calcRegColor(person)">
<span v-if="person.table_name">{{person.first_name + ' ' + person.last_name + ' - ' + person.table_name}}</span>
<span v-else>{{person.first_name + ' ' + person.last_name}}</span>
</div>
</div>
`,
methods: {
isCheckedIn(person) {
return person.reg_scan == null ? true : false;
},
isHidden(person)
{
console.log("here");
},
calcRegColor(person)
{
switch(person.registration_type)
{
case "Dean's Guest" :
return {
color: 'purple'
}
break;
case "BOO | VIP" :
return {
color: 'brown'
}
break;
case "Student" :
return {
color: 'green'
}
break;
case "Faculty":
case "Staff":
return {
color: 'blue'
}
break;
case "Alumni Club Leader":
return {
color: 'gold'
}
break;
case "Table Guest" :
return {
color: 'pink'
}
break;
default:
return {
color: 'black'
}
}
}
},
watch: {
computed() {
console.log("People and Tables Available");
}
}
});
var app = new Vue({
el: '#main',
data: {
tables: {},
people: [],
currentAlerts: [],
lastDismissed: []
},
methods: {
loadTables() {
$.ajax({
method: 'POST',
dataType: 'json',
url: base_url + 'users/getTableAssignments/' + event_id
}).done(data => {
this.tables = data;
});
},
loadPeople() {
$.ajax({
method: 'POST',
dataType: 'json',
url: base_url + 'users/getParticipants2/' + event_id
}).done(data => {
this.people = data;
this.sortSidebar(this.people);
});
},
loadCurrentAlerts() {
$.ajax({
method: 'POST',
dataType: 'json',
url: base_url + 'alerts/getAlerts/' + event_id
}).done(data => {
this.currentAlerts = data;
});
},
loadLastDismissed(num = 15)
{
$.ajax({
method: 'POST',
dataType: 'json',
url: base_url + 'alerts/getLastDismissed/' + event_id + '/' + num
}).done(data => {
this.lastDismissed = data;
});
},
setRefresh() {
setInterval(() => {
console.log("Getting People and Tables");
this.loadPeople();
this.loadTables();
}, 100000);
},
makeTablesDraggable() {
$(document).on("mouseenter", '.table', function(e){
var item = $(this);
//check if the item is already draggable
if (!item.is('.ui-draggable')) {
//make the item draggable
item.draggable({
start: (event, ui) => {
console.log($(this));
}
});
}
});
},
makePeopleDraggable() {
$(document).on("mouseenter", '.person', function(e){
var item = $(this);
//check if the item is already draggable
if (!item.is('.ui-draggable')) {
//make the item draggable
item.draggable({
appendTo: 'body',
containment: 'window',
scroll: false,
helper: 'clone',
start: (event, ui) => {
console.log($(this));
}
});
}
});
}
makeDroppable() {
$(document).on("mouseenter", ".dropzone, .table", function(e) {
$(this).droppable({
drop: function(ev, ui) {
console.log("Dropped in dropzone");
}
});
});
}
},
mounted() {
this.loadTables();
this.loadPeople();
this.loadCurrentAlerts();
this.loadLastDismissed();
this.setRefresh();
this.makeTablesDraggable();
this.makePeopleDraggable();
this.makeDroppable();
}
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.js"></script>
</head>
<div id="app">
<sidebar :people="people" :tables="tables"></sidebar>
</div>
You can change the people property in sidebar into a computed property, which will be calculated based on user's input.
So change the sidebar code to
<div v-for="person in filteredPeople" :class="[{'checked-in': isCheckedIn(person)}, 'person']" :id="person.id" :style="calcRegColor(person)">
<span v-if="person.table_name">{{person.first_name + ' ' + person.last_name + ' - ' + person.table_name}}</span>
<span v-else>{{person.first_name + ' ' + person.last_name}}</span>
</div>
and add a computed property
computed: {
filteredPeople () {
// Logic to filter data
}
}
A foolish aproach that I use, without computed properties:
JS:
new Vue({
el: '#app',
data: {
list: [],
filteredList: []
},
mounted(){
this.filteredList = this.list
},
methods: {
filter(e){
if(e.target.value === '') this.filteredList = this.list
else {
this.filteredList = []
this.list.forEach(item=>{
if(list.name.includes(e.target.value)) this.filteredList.push(item)
})
}
}
}
})
The "name" property of list object can be changed to whatever property you want to look for.
HTML:
<input #keyup="filter" id="search" type="search" required>
Related
I want to apply sorting on firstname, lastname and email but i did not undestand How We sort table in ascending and descnding order by clicking on column name in vuejs. I am tried lot of concepts on stackoverflow and other resources but they didn't seem to work . This is very silly question but I am stopped on this from many days.I'm new to Vue.js and any help would be appreciated. Image
<template>
<div class="h-full flex flex-col">
<ListFilter
ref="filter"
:class="{ 'mb-8': hasFilters || search }"
:filter="filter"
:has-filters="hasFilters"
:has-quick-filters="hasQuickFilters"
:query="query"
:search="search"
:search-placeholder="searchPlaceholder"
:filter-classes="filterClasses"
:initial-values="initialFilter"
:apply-filter="values => applyFilter(filterMapper(values))"
:apply-search="applySearch"
:clear-search="clearSearch"
>
<template #filters="props">
<slot
name="filters"
:reset="props.reset"
:filter="filter"
/>
</template>
<template #quickfilter>
<slot
name="quickfilter"
:apply-filter="applyFilter"
/>
</template>
<template #loader>
<loader
:loading="loading"
:backdrop="true"
/>
</template>
</ListFilter>
<!-- <div>
</div> -->
<vuetable
ref="vuetable"
:row-class="rowClass"
:api-mode="false"
:fields="columns"
:data-manager="dataManager"
:css="css.table"
:track-by="trackBy"
:sort-order="innerSortOrder"
:detail-row-component="detailRow"
:detail-row-options="detailOptions"
:no-data-template="noDataTemplate"
pagination-path="pagination"
#vuetable:row-clicked="handleRowClicked"
#vuetable:cell-clicked="props => $emit('cell-clicked', props)"
#vuetable:pagination-data="onPaginationData"
>
<template #empty-result>
<slot name="empty-result" />
</template>
<template #actions="props">
<div v-if="hasActions">
<ListActions :record="props.rowData">
<slot
name="actions"
:record="props.rowData"
/>
</ListActions>
</div>
</template>
<template #inline-actions="props">
<div v-if="hasInlineActions">
<InlineActions :record="props.rowData">
<slot
name="inline-actions"
:record="props.rowData"
/>
</InlineActions>
</div>
</template>
<template #detail-toggler="props">
<div v-if="hasDetailRow">
<DetailToggler
:row-data="props.rowData"
:row-index="props.rowIndex"
>
<template #default="detailProps">
<slot
name="detail-toggler"
:record="props.rowData"
:is-open="detailProps.isOpen"
:toggle-row="detailProps.toggleRow"
/>
</template>
</DetailToggler>
</div>
</template>
</vuetable>
<div
v-if="!infinityScroll"
class="pt-2"
>
<vuetable-pagination
ref="pagination"
:css="css.pagination"
#vuetable-pagination:change-page="onChangePage"
/>
</div>
</div>
</template>
<script>
import { Vuetable, VuetablePagination } from 'vue3-vuetable';
import AuthMixin from '#/components/auth/AuthMixin';
import ModalNavigation from '#/mixins/ModalNavigation';
// import Loader from '#/components/ui/Loader';
import { throttle } from 'lodash-es';
import ListFilter from '#/components/auth/list/ListFilter';
import NotifyMixin from '#/mixins/NotifyMixin';
const css = {
table: {
tableClass: 'table-auto w-full table',
tableBodyClass: '',
tableHeaderClass: 'px-4 py-2',
tableWrapper: 'overflow-x-auto flex-1',
loadingClass: 'loading',
ascendingIcon: 'blue chevron up icon',
descendingIcon: 'blue chevron down icon',
ascendingClass: 'sorted-asc',
descendingClass: 'sorted-desc',
sortableIcon: 'grey sort icon',
handleIcon: 'grey sidebar icon',
detailRowClass: 'bg-blue-100',
},
pagination: {
wrapperClass: 'flex justify-center py-4',
activeClass: 'active',
disabledClass: '',
pageClass: 'btn-paging',
linkClass: 'btn-paging',
paginationClass: '',
paginationInfoClass: 'pagination-info',
dropdownClass: '',
icons: {
first: '',
prev: '',
next: '',
last: '',
},
},
};
export default {
components: {
// Loader,
Vuetable,
VuetablePagination,
ListFilter,
},
mixins: [NotifyMixin, AuthMixin, ModalNavigation],
props: {
css: {
type: Object,
default() {
return css;
},
},
},
data() {
return {
// loading: false,
query: '',
// filter: this.filterMapper(this.initialFilter),
sort: undefined,
showFilters: false,
loading: false,
scrollContainer: null,
innerSortOrder: this.sortOrder || [],
data: [],
columns: [
{
name: 'first_name',
title: 'First Name',
class: 'w-1/4',
},
{
name: 'last_name',
title: 'Last Name',
class: 'w-1/4',
},
{
name: 'email',
title: 'Email',
class: 'w-1/4',
},
{
name: 'phone_number',
title: 'Phone Number',
class: 'w-1/4',
},
{
name: 'communities',
title: 'Communities',
class: 'w-1/4',
},
{
label: 'communities',
field: 'Communities',
class: 'w-1/4',
formatter(value) {
// console.log('ROW', value);
let communities = [];
value.community_has_leasing_agents.forEach(function (row) {
communities.push('<span class="tag">' + row.community_id + '</span>');
});
// console.log('communities=>', communities);
return communities.join('');
},
},
],
};
},
computed: {
search() {
return true;
},
searchPlaceholder() {
return 'Search by name, community, email';
},
hasFilters() {
// return !!this.$slots.filters;
return true;
},
hasQuickFilters() {
// return !!this.$slots['quickfilter'];
return true;
},
hasActions() {
// return !!this.$slots.actions;
return true;
},
hasInlineActions() {
// return !!this.$slots['inline-actions'];
return true;
},
hasDetailRow() {
// return this.detailRow !== "";
return true;
},
hasClickRowListener() {
// return this.$attrs['row-clicked'];
return true;
},
nonClickableRow() {
return (
this.onRowClick === 'none' &&
!this.hasClickRowListener &&
!(this.$route.params?.passFlowTo && this.$route.params?.passFlowTo !== this.$route.name)
);
},
detailOptions() {
return {
...this.detailRowOptions,
vuetable: this.$refs.vuetable,
};
},
},
async mounted() {
console.log('== Leasing Agents Index ==');
console.log(this.profile);
await this.getLeasingAgentsFromAPI();
},
created() {
if (!this.community) {
this.notifyError('please select a community to continue, then refresh the browser');
}
},
methods: {
async getLeasingAgentsFromAPI() {
console.log('LEASING::getLeasingAgentsFromAPI()');
this.loading = true;
return await this.$calendarDataProvider
.get('calendarGetLeasingAgents', {
customer_id: this.profile.customerId,
})
.then(res => {
console.log('LEASING::getLeasingAgentsFromAPI() result:');
console.log(res);
this.data = res;
return res;
// return this.getEvents(res);
})
.catch(err => console.log(err.message))
.finally(() => {
this.loading = false;
});
},
rowClass(dataItem) {
const classes = ['table-row', 'row'];
if (this.nonClickableRow) {
classes.push('table-row-nonclickable');
}
if (this.hasDetailRow && this.$refs.vuetable?.isVisibleDetailRow(dataItem[this.trackBy])) {
classes.push('table-row-detail-open');
}
return classes.join(' ');
},
toggleFilters() {
this.showFilters = !this.showFilters;
},
applySearch(value) {
this.query = value;
},
clearSearch() {
this.query = '';
},
applyFilter(values) {
this.filter = values;
this.$refs.vuetable?.changePage(1);
this.$refs.vuetable?.resetData();
},
doSearch: throttle(
function () {
if (this.query.length > 2 || this.query.length === 0) {
this.reload();
}
},
500,
{ trailing: true }
),
onPaginationData(paginationData) {
if (!this.infinityScroll) {
this.$refs.pagination.setPaginationData(paginationData);
}
},
onChangePage(page) {
this.$refs.vuetable.changePage(page);
},
reload() {
this.$refs.vuetable.resetData();
this.$refs.vuetable.refresh();
},
getSort({ sortField, direction }) {
// sortField: 'type&bundle.name', - sort by two fields
const fields = sortField.split('&');
if (fields.length > 1) {
return fields.map(item => {
const [fieldName, dir = direction] = item.split('|');
return `${fieldName},${dir}`;
});
}
return `${sortField},${direction}`;
},
async dataManager(/*sortOrder = [], pagination = { current_page: 1 }*/) {
// allow static data
// if (this.data) {
// return {
// data: this.data,
// };
// }
const data = await this.getLeasingAgentsFromAPI();
return {
data: data,
};
// const prevData = this.$refs.vuetable?.tableData ?? [];
// const { pageSize: size, query, filter, sort: oldSort } = this;
// const sort = sortOrder[0] ? this.getSort(sortOrder[0]) : undefined;
// this.loading = true;
// return this[this.dataProvider]
// .getList(this.resource, {
// page: pagination.current_page - 1,
// size,
// sort,
// query,
// ...this.requestParams,
// ...filter,
// })
// .then(this.responseMapper)
// .then(({ content: nextData, totalElements }) => {
// const newPagination = this.$refs.vuetable?.makePagination(totalElements, this.pageSize, pagination.current_page);
// this.sort = sort;
// this.innerSortOrder = sortOrder;
// return {
// pagination: newPagination,
// data: this.infinityScroll && oldSort === sort ? [...prevData, ...nextData] : nextData,
// };
// })
// .catch(error => {
// this.notifyError(error.message);
// return {
// pagination: this.$refs.vuetable?.tablePagination,
// data: this.$refs.vuetable?.tableData,
// };
// })
// .finally(() => (this.loading = false));
},
handleRowClicked({ data, ...rest }) {
if (this.$route.params?.passFlowTo && this.$route.params?.passFlowTo !== this.$route.name) {
this.$router.push({
name: this.$route.params?.passFlowTo,
params: {
...this.$route.params,
[this.routeIdParam]: data[this.trackBy],
},
});
} else {
switch (this.onRowClick) {
case 'edit':
this.$router.replace({ path: `${this.basePath}/${data[this.trackBy]}` });
break;
case 'details':
this.$router.replace({ path: `${this.basePath}/${data[this.trackBy]}/details` });
break;
default:
this.$emit('row-clicked', { data, ...rest });
}
}
},
handleScrollContainer(e) {
if (this.$refs.vuetable.tablePagination && e.target.scrollHeight - e.target.scrollTop - e.target.clientHeight <= 2) {
this.onChangePage('next');
}
},
},
};
</script>
<style scoped>
.tag {
display: inline-flex;
align-items: center;
overflow: hidden;
margin-right: 0.25rem;
padding-left: 0.5rem;
padding-right: 0.5rem;
padding-top: 0.25rem;
padding-bottom: 0.25rem;
border-radius: 0.0625rem;
--bg-opacity: 1;
background-color: #eaf6ff;
background-color: rgba(234, 246, 255, var(--bg-opacity));
--text-opacity: 1;
color: #105d91;
color: rgba(16, 93, 145, var(--text-opacity));
font-family: 'FrankNew', sans-serif;
font-weight: 500;
}
</style>
I'm attaching my index.vue file and image.
I have prepared a functional code example in JSFiddle of VUE field interaction.
https://jsfiddle.net/JLLMNCHR/2a9ex5zu/6/
I have a custom autocomplete component that works properly, a normal input field, and a 'Load' button which objetive is to load the value entered in the normal input in the autocomplete field.
This 'load' button is not working.
HTML:
<div id="app">
<p>Selected: {{test1}}</p>
<br>
<div>
<label>Test1:</label>
<keep-alive>
<autocomplete v-model="test1" v-bind:key="1" :items="theItems">
</autocomplete>
</keep-alive>
</div>
<br>
<label>Display this in 'test1':</label>
<input type="text" v-model=anotherField>
<button type="button" v-on:click="loadField()">Load</button>
<br>
<br>
<button type="button" v-on:click="displayVals()">Display vals</button>
</div>
<script type="text/x-template" id="autocomplete">
<div class="autocomplete">
<input type="text" #input="onChange" v-model="search"
#keyup.down="onArrowDown" #keyup.up="onArrowUp" #keyup.enter="onEnter" />
<ul id="autocomplete-results" v-show="isOpen" class="autocomplete-results">
<li class="loading" v-if="isLoading">
Loading results...
</li>
<li v-else v-for="(result, i) in results" :key="i" #click="setResult(result)"
class="autocomplete-result" :class="{'is-active':i === arrowCounter}">
{{ result }}
</li>
</ul>
</div>
</script>
VUE.JS:
const Autocomplete = {
name: "autocomplete",
template: "#autocomplete",
props: {
items: {
type: Array,
required: false,
default: () => []
},
isAsync: {
type: Boolean,
required: false,
default: false
}
},
data() {
return {
isOpen: false,
results: [],
search: "",
isLoading: false,
arrowCounter: 0
};
},
methods: {
onChange() {
// Let's warn the parent that a change was made
this.$emit("input", this.search);
// Is the data given by an outside ajax request?
if (this.isAsync) {
this.isLoading = true;
} else {
// Let's search our flat array
this.filterResults();
this.isOpen = true;
}
},
filterResults() {
// first uncapitalize all the things
this.results = this.items.filter(item => {
return item.toLowerCase().indexOf(this.search.toLowerCase()) > -1;
});
},
setResult(result) {
this.search = result;
this.$emit("input", this.search);
this.isOpen = false;
},
onArrowDown(evt) {
if (this.arrowCounter < this.results.length) {
this.arrowCounter = this.arrowCounter + 1;
}
},
onArrowUp() {
if (this.arrowCounter > 0) {
this.arrowCounter = this.arrowCounter - 1;
}
},
onEnter() {
this.search = this.results[this.arrowCounter];
this.isOpen = false;
this.arrowCounter = -1;
},
handleClickOutside(evt) {
if (!this.$el.contains(evt.target)) {
this.isOpen = false;
this.arrowCounter = -1;
}
}
},
watch: {
items: function(val, oldValue) {
// actually compare them
if (val.length !== oldValue.length) {
this.results = val;
this.isLoading = false;
}
}
},
mounted() {
document.addEventListener("click", this.handleClickOutside);
},
destroyed() {
document.removeEventListener("click", this.handleClickOutside);
}
};
new Vue({
el: "#app",
name: "app",
components: {
autocomplete: Autocomplete
},
methods: {
displayVals() {
alert("test1=" + this.test1);
},
loadField() {
this.test1=this.anotherField;
}
},
data: {
test1: '',
anotherField: '',
theItems: [ 'Apple', 'Banana', 'Orange', 'Mango', 'Pear', 'Peach', 'Grape', 'Tangerine', 'Pineapple']
}
});
Any help will be appreciated.
See this new fiddle where it is fixed.
When you use v-model on a custom component you need to add a property named value and watch it for changes, so it can update the local property this.search.
I have a custom table with actions via a modal popup that set values on Rows. Things are mostly working great (Updates to Foo and Bar get sent to the backend and are set in a database, reload of the page pulls the data from the database and shows foo/bar were correctly set). The only not-great part is on setting of Foo, the value in the table does not get updated. Bar gets updated/is reactive. (the template uses foo.name and bar.id). Does anyone have any ideas on how to get Foo to update in the table? I've changed the moustache template to use {{ foo.id }} and it updates, but I need foo.name.
<template>
<div>
<c-dialog
v-if="foo_modal"
title="Set Foo"
:actions="foo_modal_options.actions"
#cancel="foo_modal = null">
<slot>
<div class="form-group">
<label>Foo:</label>
<select class="form-control" v-model="foo_modal.thing.foo.id">
<option v-for="foo in foos" :key="foo.id" :value="foo.id">{{ foo.name }}</option>
</select>
</div>
</slot>
</c-dialog>
<c-dialog
v-if="bar_modal"
title="Set Rod/Stick"
:actions="bar_modal_options.actions"
#cancel="bar_modal = null">
<slot>
<div class="form-group">
<label>Rod:</label>
<select class="form-control" v-model="bar_modal.thing.rod.id">
<option v-for="bar in bars" :key="bar.id" :value="bar.id" v-if="bar.type === 'rod'">{{ bar.id }}</option>
</select>
</div>
<div class="form-group">
<label>Stick:</label>
<select class="form-control" v-model="bar_modal.thing.stick.id">
<option v-for="bar in bars" :key="bar.id" :value="bar.id" v-if="bar.type === 'stick'">{{ bar.id }}</option>
</select>
</div>
</slot>
</c-dialog>
<c-table-paginated
class="c-table-clickable"
:rows="grid.data"
:columns="grid.columns"
:actions="grid.actions"
:key="componentKey">
</c-table-paginated>
</div>
</template>
<script>
import fooModal from '../../components/fooModal.vue';
import barModal from '../../components/barModal.vue';
import CTablePaginated from "../../components/custom/cTable/cTablePaginated";
import cTooltip from '../../components/custom/cTooltip/cTooltip.vue';
import cDialog from '../../components/custom/cDialog/cDialog.vue';
import moment from 'moment';
export default {
components: { CTablePaginated, cTooltip, cDialog },
methods: {
loadData() {
let that = this;
that.$http.get('/things', { params: that.param || {} })
.then(function (things) {
that.things = things.data;
that.grid.data = that.things;
});
},
setBar(thing_id, options, cb) {
let that = this;
this.$http.patch(`/things/${thing_id}`, { rod_id: options.rod, stick_id: options.stick })
.then(function () {
cb();
});
},
setFoo(thing_id, options, cb) {
let that = this;
this.$http.patch(`/things/${thing_id}`, { foo_id: options.foo_id })
.then(function () {
cb();
})
},
},
data() {
return {
componentKey: 0,
things: null,
foos: [],
bars: [],
foo_modal: null,
foo_modal_options: {
actions: [
{
label: "Save",
class: "btn-primary",
action: (function (ctx) {
return function () {
const thing = ctx.foo_modal.thing;
const options = {
foo_id: thing.foo.id,
};
ctx.setFoo(thing.id, options, function () {
ctx.foo_modal = null;
});
}
})(this)
},
{
label: "Cancel",
action: (function (ctx) {
return function () {
ctx.foo_modal = null;
}
})(this)
}
]
},
bar_modal: null,
bar_modal_options: {
actions: [
{
label: "Save",
class: "btn-primary",
action: (function (ctx) {
return function () {
const thing = ctx.bar_modal.thing;
const options = {
rod: thing.rod.id,
stick: thing.stick.id
};
ctx.setBar(thing.id, options, function () {
ctx.bar_modal = null;
});
}
})(this)
},
{
label: "Cancel",
action: (function (ctx) {
return function () {
ctx.bar_modal = null;
}
})(this)
}
]
},
grid: {
data: [],
columns: [
{
label: "Foo",
value: function (row) {
if (!row.foo) return "No foo set";
return `${row.foo.name }`;
}
},
{
label: "Rod/Stick",
value: function (row) {
if (!row.rod && !row.stick) return "No rod/stick set";
if (!row.rod) return `No rod set/${row.stick.id}`;
if (!row.stick) return `${row.rod.id}/no stick set`;
return `${row.rod.id}/${row.stick.id}`;
}
}
],
actions: [
{
label: "Set Foo",
visible: function (thing) {
return !thing.active;
},
action: (function (ctx) {
return function (thing) {
if (!thing.foo) thing.foo = {};
ctx.foo_modal = {
thing: thing
};
}
})(this)
},
{
label: "Set Bar",
visible: function (thing) {
return !thing.active;
},
action: (function (ctx) {
return function (thing) {
if (!thing.rod) thing.rod = {};
if (!thing.stick) thing.stick = {};
ctx.bar_modal = {
thing: thing
};
}
})(this)
},
],
}
};
},
props: {
title: {
type: String
},
param: {
type: Object,
required: true
},
events: {
type: Object,
required: true
}
},
created() {
let that = this;
this.loadData();
this.$http.get('/bars')
.then(function (bars) {
that.bars = bars.data;
});
this.$http.get('/foos')
.then(function (foos) {
that.foos = foos.data;
});
},
}
</script>
There are two possibilities you can try both if any one of them can help you.
You can set value by using Vuejs this.$set method for deep reactivity. Click here.
You can use this.$nextTick(()=>{ // set your variable here }). Click here.
As a vuejs component, I want to be able to display a character counter next to my input field.
The field is initially set up using a prop (this.initialValue).
When the method this.updateCounter is called the input textfield is blocked : typing into the field won't update its value. If I don't set the maxlength prop, the field is working fine : I can update the textfield.
Usage in a template :
<textfield maxlength="50" name="title" initialValue="Test"></textfield>
Here is the component code :
<template>
<div class="input">
<div class="input__field">
<span class="input__limit f--small">{{ counter }}</span>
<input type="text" :name="name" :maxlength="computedMaxlength" v-model="currentValue" />
</div>
</div>
</template>
<script>
export default {
name: 'Textfield',
props: {
name: {
default: ''
},
maxlength: {
default: 0
},
initialValue: {
default: ''
}
},
computed: {
hasMaxlength: function () {
return this.maxlength > 0;
},
computedMaxlength: function () {
if(this.hasMaxlength) return this.maxlength;
else return false;
},
currentValue: {
get: function() {
return this.initialValue;
},
set: function(newValue) {
this.updateCounter(newValue);
this.$emit("change", newValue);
}
}
},
data: function () {
return {
counter: 0
}
},
methods: {
updateCounter: function (newValue) {
if(this.maxlength > 0) this.counter = this.maxlength - newValue.length;
}
},
mounted: function() {
this.updateCounter(this.initialValue);
}
}
</script>
Edit
I have fixed my issue by not using v-model but instead using a value and an input event.
data: function () {
return {
value: this.initialValue,
counter: 0
}
},
methods: {
updateCounter: function (newValue) {
if(this.maxlength > 0) this.counter = this.maxlength - newValue.toString().length;
},
onInput: function(event) {
const newValue = event.target.value;
this.value = newValue;
this.updateCounter(newValue);
this.$emit("change", newValue);
}
},
I am new to knockout and MVC. I wanted to add a link button(delete) which will delete the record that is displayed in my knockout grid. I really dont have any idea how to achieve this. I have the following code that displays the record using the KO grid. Now I want to add a link button in the grid to delete the record
CONTROLLER:
public JsonResult GetResult()
{
GetResultRequest req = new GetResultRequest() { AcctID=57345, PartyType=2 };
var getResultInfo = WSHelper.WsService.GetResults(req);
return Json(getResultInfo.Signers, JsonRequestBehavior.AllowGet);
}
VIEW:
#Styles.Render("~/Content/css")
#Scripts.Render("~/bundles/SafeHarborBundle")
<script src="~/Scripts/koGrid-2.1.1.js"></script>
<script type="text/javascript">
var dataViewModel = ko.mapping.fromJS(#Html.Raw(Json.Encode(Model)));
<div id="gridSigner">
<div id="grids123" style="height: 700px; width: 650px;"
data-bind="koGrid: {
data: gridItems, columnDefs: [{ field: 'AcctID', displayName: 'AcctID', width: '150' },
{ field: 'FName', displayName: 'First Name', width: '150' },
{ field: 'LName', displayName: 'Last Name', width: '150' },
{ field: 'AliasFName', displayName: 'Alias First Name', width: '150' },
{ field: 'SSN', displayName: 'AcctID', width: '150' }],
autogenerateColumns: false,
isMultiSelect: false,
showFilter: true,
showColumnMenu: true,
enablePaging: false,
displaySelectionCheckbox: false,
enableColumnResize: false,
multiSelect: false
}">
JQUERY FILE:
$(document).ready(function () {
loadApplication(dataViewModel);
ko.applyBindings(Gridviews, document.getElementById('gridSigner'));
});
function loadApplication(initialData) {
self = this;
self.ViewModel = initialData;
self.BranchOptions = ko.observableArray([]);
self.AcctTypeOptions = ko.observableArray([]);
self.OriginationOptions = ko.observableArray([]);
self.Message = ko.observable();
SearchSignerData();
ko.applyBindings(self, document.getElementById('main-search'));
}
SearchSignerData = function () {
$.ajax({
type: "Get",
url: "/SafeHarborApp/GetResult",
contentType: 'application/json',
async: true,
cache: false,
beforeSend: function () {
},
success: function (result) {
alert(result[0].AcctID.toString());
if (result.length != 0) {
$.each(result, function (i, item) {
Gridviews.gridItems.push(item);
});
}
else {
Gridviews.gridItems.removeAll();
alert("No Records found");
}
},
complete: function () {
},
error: function (xhr, textStatus, errorThrown) {
//alert(jqXHR.responseText);
var title = xhr.responseText.split("<title>")[1].split("</title>")[0];
alert(title);
// Handle error.
}
});
}
The above code works fine in displaying the record in the KO grid. However, I dont know how to add a delete button in the displayed KO grid now. I tried searching for it but was not able to find anything useful that will get me the result. Please help...
Use CellTemplate in ko grid.plese see code below
<script type="text/javascript">
self.NoOfAccountColumn = '<a data-bind="value: $parent.entity" onclick="Popup(this.value)">No Of Account</a>';
self.Delete = '<a data-bind="value: $parent.entity" onclick="deleteRow(this.value)">Delete</a>';
function Popup(rowItem) {
alert(rowItem.AffinityNum + ' ' + rowItem.ClientName + ' : NoOfAccount Clicked');
}
function deleteRow(rowItem) {
alert(rowItem.AffinityNum + ' ' + rowItem.ClientName + ' : Delete Clicked');
}
function isDoubleClick(oldValue, currentValue) {
var responseTime = 400;
if ((currentValue - oldValue) <= responseTime) {
self.clickTime = currentValue;
return true;
}
self.clickTime = currentValue;
return false;
};
</script>
<script src="~/Scripts/Packages/koGrid-2.1.1.js"></script>
<div id="disp">
<div id="grid" style="height: 200px; width: 600px"
data-bind="koGrid: {
data: BranchOptions,
afterSelectionChange: function (rowItem, event) {
if (event.type == 'click' && isDoubleClick(self.clickTime, event.timeStamp)) {
alert(rowItem.entity.ClientName + ' : Row DoubleClick');
}
},
columnDefs: [{ field: 'ClientName', displayName: 'Client Name', width: '*', },
{ field: 'AffinityNum', displayName: 'Affinity Num', width: '*', cellTemplate: NoOfAccountColumn },
{ field: 'AffinityID', displayName: 'Affinity ID', width: '*', cellTemplate: Delete }],
autogenerateColumns: false,
isMultiSelect: false,
showFilter: true,
showColumnMenu: true,
enablePaging: false,
displaySelectionCheckbox: false,
enableColumnResize: true,
multiSelect: false
}">
</div>
</div>