I have a vue application where I am displaying information inside of vuetify chips. When I want to click on a specific chip I want the console to log the value inside it. I tried accessing the array which the information originate from but I am getting an undefined error. Could someone look at my code and tell me what is wrong with it?
html:
<v-chip-group
v-model="selection"
active-class="deep-purple--text text--accent-4"
mandatory
>
<v-chip
v-for="(time, i) in dateTimeArray"
:key="time"
:value="time.startTime+' | '+time.endTime"
#click="pushSelected()"
>
{{ time.startTime +" : "+ time.endTime }}
</v-chip>
</v-chip-group>
Script:
export default {
name: "MeetingAdminComponent",
data : ()=>({
singleSelect: false,
selection: "",
dateTimeArray:[],
availableTimes: [
],
}),
created() {
this.getAvailableMeetingTimes()
},
methods:{
getAvailableMeetingTimes() {
var pageURL = window.location.href;
var lastURLSegment = pageURL.substr(pageURL.lastIndexOf('/') + 1);
axios.get("http://localhost:8080/api/voterAvailableTime/findBy", {
params: {
meetingName: lastURLSegment,
}
})
.then(response => (this.availableTimes = response.data)
)
},
getTimesFilteredByDate() {
var pageURL = window.location.href;
var lastURLSegment = pageURL.substr(pageURL.lastIndexOf('/') + 1);
var selectedDate = this.selectedDate
axios.get("http://localhost:8080/api/voterAvailableTime/find", {
params: {
meetingName: lastURLSegment,
date: selectedDate
}
})
.then(response => (this.dateTimeArray = response.data))
},
pushSelected(){
console.log(this.availableTimes.startTime+ " " + this.availableTimes.endTime)
}
}
};
</script>
Pass the current item as parameter to the method :
<v-chip
v-for="(time, i) in dateTimeArray"
:key="time"
:value="time.startTime+' | '+time.endTime"
#click="pushSelected(item)"
in methods:
pushSelected(item){
console.log(item.startTime+ " " + item.endTime)
}
Related
Normally in Nuxt when creating dynamic routing for things like blogs post, I would do something like the following structure.
Pages directory
pages/posts/
pages/posts/index.vue
pages/posts/_category/
pages/posts/_category/index.vue
pages/posts/_category/_sub-category/
pages/posts/_category/_sub-category/_id.vue
/pages/posts/_category/_sub-category/_id.vue
<template>
<div>
<h1>{{ title }}</h1>
</div>
</template>
<script>
import axios from 'axios'
export default {
data () {
return {
id: this.$route.params.id,
all_posts: '',
filtered_post: '',
post_data: '',
category: '',
sub_category: '',
title: ''
}
},
mounted () {
this.getSingle()
},
methods: {
getSingle () {
axios.get('someapiendpoint')
.then((response) => {
// get response data
this.all_posts = response.data
// filter response data by id
this.filtered_post = this.all_posts.filter(post => post.id === this.id)
// get data from index [0]
this.post_data = this.filtered_post[0]
// set data vars
this.category = this.post_data.category
this.sub_category = this.post_data.sub_category
this.title = this.post_data.title
})
}
}
}
</script>
Nuxt.config.js
generate: {
routes () {
return axios.get('https://someapiendpoint').then((res) => {
return res.data.map((post) => {
return {
route: '/posts/' + post.category + '/' + post.slug + '/' + post.id,
payload: (post)
}
})
})
}
},
Nuxt Links
<nuxt-link :to="{ path: '/posts/' + post.category + '/' + post.sub_category + '/' + post.id}" v-for="post in displayedPosts" :key="post.id">
{{ post.title }}
</nuxt-link>
And this would generate routes like
/posts/my-category/my-sub-category/my-article-title/12345
My question is how can I remove the ID from the URL and still get the data based on the ID but with a URL like this
/posts/my-category/my-sub-category/my-article-title/
Keeping the id on the URL is not really good for SEO. You can filter your posts only by slugs instead of IDs, a slug is unique for each post. or if you still want to use the ID as the key to filter, you can use Vuex to save the current post ID on click.
I am using a 'Custom Datatable' solution in order to modify picklist values within a datatable. Project code may be referenced here:
https://live.playg.app/play/picklist-in-lightning-datatable
I have made changes so that I can retrieve data from the custom object: Payment__c, and I am attempting modify the picklist values for the Payment_Status__c field. My 'debugging' method has been to create numerous console.log statements to verify data during the updating process. Picklist values are currently hardcoded (have not figured out how to dynamically pull from SF yet). Inline edit of individual cells works fine, and I am able to save those values as well (though changes are not reflected until I perform a manual page refresh). Picklist selection is working, but I am unable to save the currently selected picklist value in the datatable.
I believe that the intended trigger event for picklist selection changes--'valueselect', is not being fired, and the handleSelection method is not receiving this event when a new picklist selection is made.
The lightning component used on Salesforce is c-customDatatableDemo:
customDatatableDemo.js
import { LightningElement, track, wire } from 'lwc';
import getPayments from '#salesforce/apex/PaymentController.getPayments';
import saveRecords from '#salesforce/apex/PaymentController.saveRecords';
import { updateRecord } from 'lightning/uiRecordApi';
import { refreshApex } from '#salesforce/apex';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
export default class CustomDatatableDemo extends LightningElement {
#track data = [];
//have this attribute to track data changed
//with custom picklist or custom lookup
#track draftValues = [];
#track lastSavedData = [];
connectedCallback() {
this.columns = [
{
label: 'Name',
fieldName: 'Name',
editable: false
}, {
label: 'Invoice Number',
fieldName: 'Invoice_Number__c',
editable: true
}, {
label: 'Invoice Amount',
fieldName: 'Invoice_Amount__c',
type: 'currency',
editable: true
}, {
label: 'Invoice Date',
fieldName: 'Invoice_Date__c',
type: 'date',
editable: true
}, {
label: 'Payment Status',
fieldName: 'Payment_Status__c',
type: 'picklist',
typeAttributes:
{
placeholder: 'Choose Status',
options: [
{ label: 'Needs to Be Paid', value: 'Needs to Be Paid' },
{ label: 'Issued', value: 'Issued' },
{ label: 'Voided', value: 'Voided' },
] // List of Payment Status picklist options
, value: {fieldName: 'Payment_Status__c' } // default value for picklist
, context: {fieldName: 'Id' } // binding Payment Id with context variable to be returned back
}
},
{
label: 'Description', fieldName: 'Work_Description__c', type: 'text', editable: true
}];
// Get Payments data
getPayments()
.then(result => {
this.data = result;
this.error = undefined;
})
.catch(error => {
this.error = error;
this.data = undefined;
})
// Save last saved copy
this.lastSavedData = JSON.parse(JSON.stringify(this.data));
}
updateDataValues(updateItem) {
console.log('START--updateDataValues()');
let copyData = [... this.data];
copyData.forEach(item => {
if (item.Id === updateItem.Id) {
for (let field in updateItem) {
console.log('updateDataValues() item.Id = ' + JSON.stringify(updateItem.Id));
console.log('updateItem[field] = ' + JSON.stringify(updateItem[field]));
item[field] = updateItem[field];
console.log('UPDATED--item[field] = ' + updateItem[field]);
}
}
});
//write changes back to original data
this.data = [...copyData];
console.log('this.data = ' + JSON.stringify(this.data));
let tempData = [...this.data];
//console.log('tempData = ' + JSON.stringify(tempData));
console.log('END--updateDataValues()');
}
updateDraftValues(updateItem) {
console.log('START--updateDraftValues()');
console.log('stringify draft updateItem = ' + JSON.stringify(updateItem));
let draftValueChanged = false;
let copyDraftValues = [...this.draftValues];
//store changed value to do operations
//on save. This will enable inline editing &
//show standard cancel & save button
let i = 0;
copyDraftValues.forEach(item => {
if (item.Id === updateItem.Id) {
i++;
console.log('i = ' + i);
for (let field in updateItem) {
console.log(i + '. UpdateDraftValues--item id if selected...item Id = ' + item.Id + ' & item value = ' + item.value);
item[field] = updateItem[field];
console.log('item[field] = ' + updateItem[field]);
}
draftValueChanged = true;
console.log('draftValueChanged = TRUE');
}
});
//draftValueChanged = true;
if (draftValueChanged) {
console.log('YESdraftValueChanged');
console.log('copyDraftValues = ' + JSON.stringify(copyDraftValues));
this.draftValues = [...copyDraftValues];
//console.log('draftValues = ' + JSON.stringify(draftValues));
} else {
console.log('NOdraftValue!Changed');
this.draftValues = [...copyDraftValues, updateItem];
let testDraftValues = {... this.draftValues};
console.log('JSON.stringify(testDraftValues) = ' + JSON.stringify(testDraftValues));
}
console.log('STOP--updateDraftValues()')
}
//listener handler to get the context and data
//updates datatable
picklistChanged(event) {
console.log('START--picklistChanged()');
console.log('EVENT type - ' + event.type);
event.stopPropagation();
let dataReceived = event.detail.data;
let updatedItem = { ...dataReceived };
console.log('picklistChanged()...updatedItem = ' + JSON.stringify(updatedItem));
this.updateDraftValues(updatedItem);
this.updateDataValues(updatedItem);
/* console.log('event.value = ' + event.value);
this.value = event.target.value;
event.stopPropagation();
let dataReceived = event.detail.data;
let updatedItem = { ...dataReceived };
console.log('updatedItem.context ' + updatedItem.context);
console.log('updatedItem.value ' + updatedItem.value);
console.log('updatedItem = ' + JSON.stringify(updatedItem));
this.updateDraftValues(updatedItem);
this.updateDataValues(updatedItem);
console.log('picklistChanged() = ' + JSON.stringify(updatedItem)); */
console.log('STOP--picklistChanged()');
}
handleSelection(event) {
console.log('START--handleSelection()');
this.updateDraftValues(event.detail.draftValues[0]);
console.log('this.updateDraftValues(event.detail.draftValues[0]);')
/* event.stopPropogation();
let dataReceived = event.detail.data;
let updatedItem = { ...dataReceived };
this.updateDraftValues(updatedItem);
this.updateDraftValues(updatedItem); */
console.log('STOP--handleSelection() = ' + JSON.stringify(updatedItem));
}
//handler to handle cell changes & update values in draft values
handleCellChange(event) {
console.log('START--handleCellChange()');
console.log('handleCellChange');
this.updateDraftValues(event.detail.draftValues[0]);
console.log('handleCellChange value = ' + JSON.stringify(this.updateDraftValues));
console.log('END--handleCellChange()');
}
handleSave(event) {
if (event.type === 'picklistchanged'){
}
console.log('START--handleSave');
console.log('Updated items = ', this.draftValues);
// save last saved copy
this.lastSavedData = JSON.parse(JSON.stringify(this.data));
console.log('this.lastSavedData = ' + JSON.stringify(this.lastSavedData));
this.fldsItemValues = event.detail.draftValues;
console.log('this.fldsItemValues = ' + JSON.stringify(this.fldsItemValues));
const inputsItems = this.fldsItemValues.slice().map(draft => {
const fields = Object.assign({}, draft);
console.log('JSON.stringify() fields ' + JSON.stringify(fields));
return { fields };
});
// Show toast after successful update
const promises = inputsItems.map(recordInput => updateRecord(recordInput));
Promise.all(promises).then(res => {
this.dispatchEvent(
new ShowToastEvent({
title: 'Success',
message: 'Records Updated Successfully!!',
variant: 'success'
})
);
this.fldsItemValues = [];
return this.refresh();
}).catch(error => {
this.dispatchEvent(
new ShowToastEvent({
title: 'Error',
message: 'An Error Occured!!',
variant: 'error'
})
);
}).finally(() => {
// Clear draft values
this.draftValues = [];
});
// Refresh the window after successful save
//window.open('url','_self');
//document.location.reload(true);
//cmp.find("table-component-id").set("v.draftValues", null);
console.log('END--handleSave');
}
handleCancel(event) {
//remove draftValues & revert data changes
this.data = JSON.parse(JSON.stringify(this.lastSavedData));
this.draftValues = [];
}
async refresh() {
console.log('async refresh');
await refreshApex(this.data);
//this.connectedCallback();
}
}
customDatatableDemo.html
<template>
<lightning-card title="Invoicing" icon-name="custom:custom17">
<div class="slds-var-m-around_medium">
<template if:true={data}>
<c-custom-data-table
object-api-name="Payment__c"
key-field="Id"
data={data}
value=""
show-row-number-column
columns={columns}
onpicklistchanged={picklistChanged}
onvalueselect={handleSelection}
draft-values={draftValues}
oncellchange={handleCellChange}
onsave={handleSave}
oncancel={handleCancel}>
</c-custom-data-table>
<template if:true={data.error}></template>
</template>
</div>
</lightning-card>
<p>Selected value is: {value}</p>
</template>
customDataTable.js
import LightningDatatable from 'lightning/datatable';
//import the template so that it can be reused
import DatatablePicklistTemplate from './picklist-template.html';
import { loadStyle } from 'lightning/platformResourceLoader';
import CustomDataTableResource from '#salesforce/resourceUrl/CustomDataTable';
export default class CustomDataTable extends LightningDatatable {
static customTypes = {
picklist: {
template: DatatablePicklistTemplate,
typeAttributes: ['label', 'placeholder', 'options', 'value', 'context'],
},
};
constructor() {
super();
Promise.all([
loadStyle(this, CustomDataTableResource),
]).then(() => {})
}
}
picklist-template.html (Same folder as customDataTable)
<template>
<c-datatable-picklist label={typeAttributes.label} value={typeAttributes.value}
placeholder={typeAttributes.placeholder} options={typeAttributes.options} context={typeAttributes.context}>
</c-datatable-picklist>
</template>
datatablePicklist.js
import { LightningElement, api, track } from 'lwc';
export default class DatatablePicklist extends LightningElement {
#api label;
#api placeholder;
#api options;
#api value;
#api context;
handleChange(event) {
//show the selected value on UI
this.value = event.detail.value;
//fire event to send context and selected value to the data table
this.dispatchEvent(new CustomEvent('picklistchanged', {
composed: true,
bubbles: true,
cancelable: true,
detail: {
data: { context: this.context, value: this.value }
}
}));
}
}
datatablePicklist.html
<template>
<div class="picklist-container">
<lightning-combobox name="picklist" label={label} value={value} placeholder={placeholder} options={options}
onchange={handleChange}></lightning-combobox>}
</div>
</template>
lwcEditSaveRow.js
import { LightningElement, wire, track } from 'lwc';
import getAccounts from '#salesforce/apex/lwcEditSaveRowCtrl.getAccounts';
import { updateRecord } from 'lightning/uiRecordApi';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import { refreshApex } from '#salesforce/apex';
const columns = [
{
label: 'Name',
fieldName: 'Name',
type: 'text',
}, {
label: 'Phone',
fieldName: 'Phone',
type: 'phone',
editable: true,
}, {
label: 'Industry',
fieldName: 'Industry',
type: 'text',
editable: true,
}, {
label: 'Type',
fieldName: 'Type',
type: 'text',
editable: true
}, {
label: 'Description',
fieldName: 'Type',
type: 'text',
editable: true
}
];
export default class LwcEditSaveRow extends LightningElement {
columns = columns;
#track accObj;
fldsItemValues = [];
#wire(getAccounts)
cons(result) {
this.accObj = result;
if (result.error) {
this.accObj = undefined;
}
};
saveHandleAction(event) {
this.fldsItemValues = event.detail.draftValues;
const inputsItems = this.fldsItemValues.slice().map(draft => {
const fields = Object.assign({}, draft);
return { fields };
});
const promises = inputsItems.map(recordInput => updateRecord(recordInput));
Promise.all(promises).then(res => {
this.dispatchEvent(
new ShowToastEvent({
title: 'Success',
message: 'Records Updated Successfully!!',
variant: 'success'
})
);
this.fldsItemValues = [];
return this.refresh();
}).catch(error => {
this.dispatchEvent(
new ShowToastEvent({
title: 'Error',
message: 'An Error Occured!!',
variant: 'error'
})
);
}).finally(() => {
this.fldsItemValues = [];
});
}
async refresh() {
await refreshApex(this.accObj);
}
}
lwcEditSaveRow.html
<template>
<lightning-card>
<div class="slds-m-around_medium">
<h3 class="slds-text-heading_medium"><lightning-icon icon-name="custom:custom84" size="small"></lightning-icon> <strong style="color:#270086; font-size:13px; margin-right:5px;"> How to inline Edit/Save Rows With Lightning Datatable in Lightning Web Component (LWC) </strong></h3>
<br/><br/>
<template if:true={accObj.data}>
<lightning-datatable key-field="Id"
data={accObj.data}
columns={columns}
onsave={saveHandleAction}
draft-values={fldsItemValues}
hide-checkbox-column
show-row-number-column>
</lightning-datatable>
</template>
<br/>
<br/>
<!--Start RelatedTopics Section-->
<div style="border:1px #ddd solid; padding:10px; background:#eee; margin:40px 0;">
<p data-aura-rendered-by="435:0"><img src="https://www.w3web.net/wp-content/uploads/2021/05/thumbsUpLike.png" width="25" height="25" style="vertical-align:top; margin-right:10px;" data-aura-rendered-by="436:0"><strong data-aura-rendered-by="437:0"><span style="font-size:16px; font-style:italic; display:inline-block; margin-right:5px;">Don't forget to check out:-</span>An easy way to learn step-by-step online free Salesforce tutorial, To know more Click <span style="color:#ff8000; font-size:18px;" data-aura-rendered-by="442:0">Here..</span></strong></p>
<br/><br/>
<p data-aura-rendered-by="435:0"><img src="https://www.w3web.net/wp-content/uploads/2021/07/tickMarkIcon.png" width="25" height="25" style="vertical-align:top; margin-right:10px;" data-aura-rendered-by="436:0"><strong data-aura-rendered-by="437:0"><span style="font-size:17px; font-style:italic; display:inline-block; margin-right:5px; color:rgb(255 128 0);">You May Also Like →</span> </strong></p>
<div style="display:block; overflow:hidden;">
<div style="width: 50%; float:left; display:inline-block">
<ul style="list-style-type: square; font-size: 16px; margin: 0 0 0 54px; padding: 0;">
<li>How to get selected checkbox value in lwc</li>
<li>how to display account related contacts based on AccountId in lwc</li>
<li>how to create lightning datatable row actions in lwc</li>
<li>how to use if and else condition in lwc</li>
<li>how to display selected radio button value in lwc</li>
</ul>
</div>
<div style="width: 50%; float:left; display:inline-block">
<ul style="list-style-type: square; font-size: 16px; margin: 0 0 0 54px; padding: 0;">
<li>display account related contacts based on account name in lwc</li>
<li>how to insert a record of account Using apex class in LWC</li>
<li>how to get picklist values dynamically in lwc</li>
<li>how to edit/save row dynamically in lightning component</li>
<li>update parent field from child using apex trigger</li>
</ul>
</div>
<div style="clear:both;"></div>
<br/>
<div class="youtubeIcon">
<img src="https://www.w3web.net/wp-content/uploads/2021/11/youtubeIcon.png" width="25" height="25" style="vertical-align:top; margin-right:10px;"/> <strong>TechW3web:-</strong> To know more, Use this <span style="color: #ff8000; font-weight: bold;">Link</span>
</div>
</div>
</div>
<!--End RelatedTopics Section-->
</div>
</lightning-card>
</template>
Example of changing and saving non-picklist value in datatable:
Changing and saving non-picklist value
Example of changing and saving a picklist value:
Changing and saving picklist value (1)
Last bit of console output:
Changing and saving picklsit value (2)
As this is my first time working with Lightning Web components, I would greatly appreciate any assistance you may provide. Thanks in advance.
I was able to get this custom data table component working for something I am developing to effectively bind records as rows. Here 2 differences I notice:
I did not include onvalueselect and oncellchange methods for the component html declaration, only the onpicklistchanged.
You may want to use your custom server side controller method instead of the built-in uiRecordApi->updateRecord one. Something tells me this may not play nice with row data from the data table. In my implementation, I was simply able to pass the draftValues over to the server side method which has a single parameter of list of sObject:
async saveRecords(event){
const updatedFields = event.detail.draftValues;
this.draftValues = [];
this.showSpinner = true
try{
await saveRelatedRecords({sObjs: updatedFields}) // server side save
.then((result) => {
this.updateMessage = result;
})
this.showSpinner = false;
if(this.updateMessage == 'success'){
this.showToast('Success', 'Record(s) Updated', 'success');
} else{
this.showToast('Error', this.updateMessage, 'error');
}
await refreshApex(this._wiredRecordData);
this.unsavedData = this.records;
} catch (error) {
this.showSpinner = false;
this.showToast('Error while updating or refreshing records', error.body.message, 'error');
}
}
In regards to your data not refreshing, I suggest you wire your getPayments method so that you can always get a fresh set from the server side, rather than trying to keep track of and maintain data changes on the client side, something like:
_wiredRecordData;
#wire(getRelatedRecords)
relatedRecords(getRecsResult){
const { data, error } = getRecsResult;
this._wiredRecordData = getRecsResult;
if(data){
this.records = data;
}
}
Then after your success toast in your save method, you can use
await refreshApex(_wiredRecords); and lwc knows to rerender based on the wiring (or at least I think that's how it works.)
Lastly, here is the server side controller method I have to dynamically generate column header information so it does not need to be hard coded into the component. However I did need to modify the custom component a bit to include a new "fieldapi" attribute so that the client side method knows what field to set for the changed value during the onpicklistchanged action.
#AuraEnabled(cacheable=true)
public static String getColumnHeaders(String sObjAPI, String fieldAPIs)
{
List<ColumnHeaderInfo> colHeaders = new List<ColumnHeaderInfo>();
Schema.DescribeSObjectResult sObjDesc = Schema.getGlobalDescribe().get(sObjAPI).getDescribe();
Boolean objIsUpdateable = sObjDesc.isUpdateable();
Map<String, Schema.SObjectField> objFields = sObjDesc.fields.getMap();
for(String field: fieldAPIs.split(','))
{
if(!objFields.keySet().contains(field.toLowerCase())){
continue;
}
Schema.DescribeFieldResult fieldDesc = objFields.get(field).getDescribe();
if(!fieldDesc.isAccessible()){
continue;
}
ColumnHeaderInfo colHeader = new ColumnHeaderInfo();
colHeader.label = fieldDesc.getLabel();
colHeader.fieldName = fieldDesc.getName();
colHeader.editable = fieldDesc.isUpdateable() && sObjDesc.isUpdateable();
colHeader.type_x = fieldDesc.getType().name().toLowerCase();
if(colHeader.type_x == 'picklist')
{
colHeader.type_x = 'picklist';
List<Schema.PicklistEntry> picklistValues = fieldDesc.getPicklistValues();
colHeader.typeAttributes = new TypeAttributes();
colHeader.typeAttributes.options = new List<Option>();
for(Schema.PicklistEntry ple: picklistValues)
{
Option opt = new Option();
opt.value = ple.getValue();
opt.label = ple.getLabel();
colHeader.typeAttributes.options.add(opt);
}
colHeader.typeAttributes.context = new FieldName();
colHeader.typeAttributes.context.fieldName = 'Id';
colHeader.typeAttributes.value = new FieldName();
colHeader.typeAttributes.value.fieldName = fieldDesc.getName();
colHeader.typeAttributes.fieldapi = fieldDesc.getName();
}
// multi-select picklist fields not supported so make them read-only
if(colHeader.type_x == 'multipicklist'){
colHeader.editable = false;
}
colHeaders.add(colHeader);
}
return JSON.serialize(colHeaders).replaceAll('type_x', 'type');
}
private class ColumnHeaderInfo
{
public String label;
public String fieldName;
public String type_x;
public Boolean editable;
public TypeAttributes typeAttributes;
}
private class TypeAttributes
{
public String placeholder;
public List<Option> options;
public FieldName value;
public FieldName context;
public FieldName label;
public FieldName tooltip;
public String fieldapi;
public String target;
}
private class Option
{
public String label;
public String value;
}
private class FieldName
{
public String fieldName;
}
i'm trying to get vue-router to work with blogger feeds json api, i managed to make it work but on reload it goes back to the first page, i tried to add html components and template in routes parameter but it did not work, i tried everything i begun to wonder if it is even possible, here is my code:
new Vue({
el: '#app',
router: new VueRouter({}),
vuetify: new Vuetify({}),
data() {
return {
feedAPI: '/feeds/posts/default?alt=json&start-index=',
items_all: [],
items: [],
Totalposts: null,
Totalpages: null,
Startindex: 1,
pageNumber: null,
keyword: '',
results: [],
Postsperpage: 5,
}
},
methods: {
getPosts() {
axios.get(this.feedAPI + this.Startindex + '&max-results=' + this.Postsperpage).then(async (response) => {
const items = await response.data;
this.items_all = items.feed;
this.items = this.items_all.entry;
var totalPosts = this.items_all.openSearch$totalResults.$t;
this.Totalposts = totalPosts;
var itemsPerPage = this.items_all.openSearch$itemsPerPage.$t;
this.Postsperpage = itemsPerPage;
var totalPages = Math.ceil(this.Totalposts / this.Postsperpage);
this.Totalpages = totalPages;
this.$router.push({
query: Object.assign({}, this.$route.query.pageNumber, {
page: this.pageNumber || 1
})
});
this.$nextTick(() => {
this.pageNumber
});
})
},
onPageChange() {
this.Startindex = Math.ceil((this.pageNumber * this.Postsperpage) - (this.Postsperpage - 1));
this.getPosts();
},
top() {
window.scrollTo({
top: 0,
behavior: 'smooth'
});
},
getResults() {
if (this.keyword.length > 2) {
axios.get("/feeds/posts/default?alt=json&q=" + this.keyword).then(res => (this.results = res.data.feed.entry)).catch(err => console.log(err));
}
}
},
watch: {
keyword: function(newVal) {
if (newVal.length > 3) {
this.getResults();
}
}
},
computed: {},
created() {
this.getResults()
},
mounted() {
this.getPosts();
}
});
for the html :
<v-text-field v-model="keyword" #input="getResults" placeholder="Type to Search"></v-text-field>
<div v-if="getResults">
<span v-for="result in results">
<a v-for="i in result.link" v-if="i.rel == 'alternate'" :href="i.href" :title="result.title.$t" v-html="i.title"></a>
<br />
</span>
</div>
<div v-for="item in items">
<h3><a v-for="i in item.link" v-if="i.rel == 'alternate'" :href="i.href" :title="item.title.$t" v-html="i.title"></a></h3>
</div>
<v-pagination v-model="pageNumber" :length="Totalpages" #input="onPageChange" prev-icon="mdi-menu-left" next-icon="mdi-menu-right" v-on:click.native="top"></v-pagination>
postman.response.txt
https://gist.github.com/stanislavgr79/e82999e5ae69876f0316280687388a25
var app = new Vue({
el: "#app3",
data: {
path: "",
sortEvent: "",
eventsValue: [],
},
methods: {
getResponse(){
this.requestByParam(this.sortEvent);
},
requestByParam: function (byParam) {
this.$http
.get(this.path, {
params: { sortEvent: this.sortEvent },
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
})
.then((response) =>
response.json().then((data) => {
let listResultQuery = [];
if (data.length == 0) {
return;
}
// data.forEach((element) => {
// listResultQuery.push(element);
// dont work
});
this.eventsValue = data;
this.emptyMessage = "";
})
);
},
},
});
<div id="app3">
<events_nav path=${resource.path}></events_nav>
<all_events id="all-events" :eventsValue="eventsValue"></all_events>
</div>
i try reformat:
$.ajax({
type: method_event,
url: path_event + '.sort.json',
data: params,
contentType: 'application/json',
success: function (response, status, request) {
if (status == 'success') {
var output = "";
$.each(response, function (key, value) {
output += "<div class='span3'>";
output += "<h3>" + key + "<i class='events__" + key + "'></i></h3>";
$(value).each(function (index, el) {
output += "<ul class='icons icons_type'><i class='icon-" + el.topic + "'></i>";
output += "<li class='events_type'>";
output += "<span class='date' type='date'>" + formatDate(el.eventStartDate) + "</span>";
output += "<h4><a href='"+el.titleLink+"' rel='"+el.typeOfOpen+"'>" + el.title + "</a></h4>";
output += el.description;
output += "</li></ul>";
});
output += "</div>";
$('#all-events').html(output);
});
}
}
})
}
now i have error :
Vue.component("all_events", {
props: {
eventsValue: Array,
},
template:
'<div class="span3" v-for="(value, name) in eventList">' +
'<h3>{{ name }}<i class="events__{{ name }}"></i></h3>' +
'</div>',
});
eventsValue - its Object ????? its Array ???????
what i need to write tempalate to see key
$.each(response, function (key, value) {
output += "<div class='span3'>";
output += "<h3>" + key + "<i class='events__" + key + "'></i></h3>";
this method dont work:
<ul id="example-1">
<li v-for="item in items" :key="item.message">
{{ item.message }}
</li>
</ul>
and this dont work:
<ul id="example-2">
<li v-for="(item, index) in items">
{{ parentMessage }} - {{ index }} - {{ item.message }}
</li>
</ul>
and this dont work:
<ul id="v-for-object" class="demo">
<li v-for="value in object">
{{ value }}
</li>
</ul>
and this dont work:
<div v-for="(value, name) in object">
{{ name }}: {{ value }}
</div>
and this dont work:
<div v-for="(value, name, index) in object">
{{ index }}. {{ name }}: {{ value }}
</div>
For the error "Cannot use v-for on stateful component root element because it renders multiple elements"
You just need to wrap the template in another dom element
example:
Vue.component("all_events", {
props: {
eventsValue: Array,
},
template:`
<div>
<div class="span3" v-for="(value, name) in eventList">
<h3>{{ name }}<i class="events__{{ name }}"></i></h3>
</div>
</div>
`});
try that with the code before you reformatted.
this code works. thanks community and Daniel
Vue.component("events_nav", {
props: {
dataPath: String,
},
data() {
return {
sortEvent: "topic",
topic: true,
type: false
};
},
methods: {
requestTopic: function () {
this.sortEvent = "topic";
this.$root.sortEvent = this.sortEvent;
this.topic = true;
this.type = false;
this.$root.getResponse();
},
requestType: function () {
this.sortEvent = "type";
this.$root.sortEvent = this.sortEvent;
this.topic = false;
this.type = true;
this.$root.getResponse();
},
},
created: function () {
let servletSelector = ".sort";
let servletExtension = ".json";
this.$root.dataPath = this.dataPath.concat(
servletSelector,
servletExtension
);
this.$root.sortEvent = this.sortEvent;
this.$root.getResponse();
},
template:
'<div class="navbar events_nav">' +
'<div class="navbar-inner">' +
'<span class="brand">View By:</span>' +
'<ul class="nav" id="event_sort" data-sort="topic" data-method="GET" :data-path="dataPath">' +
'<li :class="{active: topic}" id="events__view-topic"><span #click="requestTopic">Topic</span></li>' +
'<li :class="{active: type}" id="events__view-type"><span #click="requestType">Type</span></li>' +
'</ul>' +
'</div>' +
'</div>',
});
Vue.component("all-events", {
props: {
eventsValue: "",
},
template:
'<div class="row event-listing">' +
'<div class="span3" v-for="(value, name) in eventsValue">' +
'<h3>{{ name }}<event-icon :icon="name"></event-icon></h3>' +
'<event-column :value="value"></event-column>' +
'</div>' +
'</div>',
});
Vue.component("event-icon", {
props: {
icon: String,
},
computed: {
classIcon: function () {
let icon = '';
if (this.$props.icon == 'Database') {
icon = 'icon-hdd'
}
if (this.$props.icon == 'Cloud') {
icon = 'icon-cloud'
}
if (this.$props.icon == 'Mobile') {
icon = 'icon-mobile-phone'
}
if (this.$props.icon == 'Other Topics') {
icon = 'icon-calendar'
}
return icon;
}
},
template:
'<i :class="classIcon"></i>',
});
Vue.component("event-column", {
props: {
value: Array,
},
template:
'<ul class="unstyled" >' +
'<li class="event-list" v-for="item in this.$props.value">' +
'<element-event :element="item"></element-event>' +
'</li>' +
'</ul>',
});
Vue.component("element-event", {
props: {
element: Object,
},
data() {
return {
description: "",
eventdate: ""
};
},
computed: {
classIcon: function () {
let icon = '';
if (this.$props.element.topic == 'Database') {
icon = 'icon-hdd'
}
if (this.$props.element.topic == 'Cloud') {
icon = 'icon-cloud'
}
if (this.$props.element.topic == 'Mobile') {
icon = 'icon-mobile-phone'
}
if (this.$props.element.topic == 'Other Topics') {
icon = 'icon-calendar'
}
return icon;
},
selectTopic: function () {
let result = false;
if (this.$root.sortEvent == "type") {
result = true;
}
return result;
}
},
methods: {
formatDate() {
return new Date(this.$props.element.eventStartDate).toLocaleString('en-US', {
day: '2-digit',
month: 'long'
});
},
},
template:
'<div>' +
'<i v-if="selectTopic" class="icon" v-bind:class="classIcon"></i>' +
'<span class="date" type="date" v-html="formatDate()"></span>' +
'<h4><a :href="element.titleLink" :rel="element.typeOfOpen" v-html="element.title"></a></h4>' +
'<p class="event-description" v-html="element.description"></p>' +
'</div>',
})
var app = new Vue({
el: "#eventviewer-v2",
data: {
dataPath: "",
sortEvent: "",
events: "",
},
methods: {
getResponse() {
this.requestByParam(this.sortEvent);
},
requestByParam: function (byParam) {
this.$http
.get(this.dataPath, {
params: { sortEvent: this.sortEvent },
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
})
.then((response) =>
response.json().then((data) => {
this.events = data;
this.emptyMessage = "";
})
);
},
},
});
To remove wrap element...
mounted () {
this.$el.replaceWith(...this.$el.childNodes)
}
I'm trying to reference child nodes of a firebase database using a for loop. I'm using Vue and Vue-fire. The problem is that in the following code, categories[addItem.category] doesn't reference the correct data.
<el-select v-model="addItem.category" placeholder="Select a category." id="category-select">
<el-option
v-for="(val, key) in categories"
:key="val['.key']"
:label="val['.key']"
:value="val['.key']">
</el-option>
</el-select>
<el-button #click="showAdd=true">new category</el-button>
<el-select v-model="addItem.subcategory" placeholder="Select a subcategory." id="subcategory-select" v-show="addItem.category!=''">
<el-option
v-for="subcat in categories[addItem.category]"
:key="subcat['.key']"
:label="subcat['.key']"
:value="subcat">
</el-option>
</el-select>
<el-button v-show="addItem.category!=''" #click="showAdd=true">add subcategory</el-button>
I am trying to get all the keys of the selected category, which should give 'machinery' if 'mechanical' is selected. Currently, selecting 'mechanical' makes categories[addItem.category] equal to undefined. Here is what the data looks like in my db:
[![enter image description here][1]][1]
Can anyone tell me why my firebase reference categories[addItem.category] isn't referencing the child values?
If it helps, this is how I save the data:
methods: {
add(){
var updates = {};
if (this.addItem.category==''){
updates['/' + this.addItem.text + '/'] = "null";
}
else if (this.addItem.subcategory==''){
console.log('adding a subcategory: ' + this.addItem.subcategory);
console.log(this.addItem.category + ' is the category name');
updates['/' + this.addItem.category + '/' + this.addItem.text + '/'] = "null";
}
db.ref('categories').update(updates).then((successMessage) => {
// successMessage is whatever we passed in the resolve(...) function above.
// It doesn't have to be a string, but if it is only a succeed message, it probably will be.
console.log("Yay! " + successMessage);
});
Which references the following data:
data(){ return {
addItem: {
open: false,
count: 0,
category: '',
subcategory: '',
kks: {
name: ''
},
document: {
name: ''
},
product: {
name: ''
},
text: ''
},
}}
}
and here is the firebase property:
firebase: function(){
return {
categories: db.ref('categories')
}
}
[1]: https://i.stack.imgur.com/hYZN6.png
Here's what I ended up doing. The following was added as a computed property:
subcategories: function(){
if (this.addItem.category){
var val;
db.ref('categories/' + this.addItem.category).on('value', function(snapshot){
val = snapshot.val();
});
return val;
}
return this.categories;
}