How to pass parameter for dynamic route? - vue.js

I need on click go to the next page which is created with a dynamic route. It gets the id for the route from a vuex store. When I'm clicking it gives this url
http://localhost:8080/worklist/%7Bname:'worklistDynamic',%20params:%7B%20id:sideSwiperItems[indx+1].id%7D%7D
---------------------------------------
here is my code:
//html
.side-button-next(#click='switchPage()')
//function
--------------------------
switchPage() {
this.$router.push(
`{name:'worklistDynamic', params:{ id:this.sideSwiperItems[this.indx+1].id}}`,
)
},
--------------------------
computed: {
sideSwiperItems() {
return this.$store.state.buildingData.sideSwiperItems
},
indx() {
if (this.$store.state.buildingData.index === null) {
return 0
}
return this.$store.state.buildingData.index
},
},

Try to remove the backticks:
switchPage() {
let path = { name: 'worklistDynamic', params: { id: this.sideSwiperItems[this.indx + 1].id } }
// or you can write the full path with backticks and interpolation
let path = `/worklistDynamic/${this.sideSwiperItems[this.indx + 1].id}`
this.$router.push(path)
}

Related

Vue js data value is not changing after assign

I have defined the data like this
data() {
return {
mdrender: '',
markdown: ''
};
},
And I have this function :
methods: {
interpretVars: function(markdown) {
$.getJSON("/api/v1/getdoc?code=" + this.$route.query.code, function (result) {
var interpreted = markdown.replace(/\{\#(companyName)\#\}/g, 'Demo')
.replace(/\{\#(docType)\#\}/g, result[0].datas.category).replace(/\{\#(version)\#\}/g, result[0].datas.version)
.replace(/\{\#(docTitle)\#\}/g, result[0].datas.title);
this.markdown = interpreted;
console.log(interpreted);
return interpreted;
});
}
},
Now the problem is that the markdown data value does not take the new value, while the variable that I'm console logging interpreted have the correct value.
I'm doing something wrong?
Thanks in advance for replying.
Your problem is the use of the function() statement. So you will loose the scope and this doesn't represents to the current Vue instance. There are two possible solutions to fix this:
Use an arrow function:
methods: {
interpretVars: function(markdown) {
$.getJSON("/api/v1/getdoc?code=" + this.$route.query.code, (result) => {
…
});
}
},
Use a helper variable:
methods: {
interpretVars: function(markdown) {
var $this = this;
$.getJSON("/api/v1/getdoc?code=" + this.$route.query.code, function (result) {
…
$this.markdown = interpreted;
});
}
},
I guess the best way of doing this would be doing it like this :
methods: {
async interpretVars(markdown) {
$.getJSON("/api/v1/getdoc?code=" + this.$route.query.code, function (result) {
var interpreted = markdown.replace(/\{\#(companyName)\#\}/g, 'Demo')
.replace(/\{\#(docType)\#\}/g, result[0].datas.category).replace(/\{\#(version)\#\}/g, result[0].datas.version)
.replace(/\{\#(docTitle)\#\}/g, result[0].datas.title);
this.markdown = interpreted;
console.log(interpreted);
return interpreted;
});
}
This should work as expected i guess, please don't assign this to temp variable.
Store this scope variable to a temporary variable and use that variable.
methods: {
interpretVars: function(markdown) {
let that = this;
$.getJSON("/api/v1/getdoc?code=" + this.$route.query.code, function (result) {
var interpreted = markdown.replace(/\{\#(companyName)\#\}/g, 'Demo')
.replace(/\{\#(docType)\#\}/g, result[0].datas.category).replace(/\{\#(version)\#\}/g, result[0].datas.version)
.replace(/\{\#(docTitle)\#\}/g, result[0].datas.title);
that.markdown = interpreted;
console.log(interpreted, that.markdown);
return interpreted;
});
}
},

How to implement Ngx-Datatable server side pagination if pagination is not zero based

I am trying to implement server-side pagination in angular 5 based web app.
Problem is the API requires pagination to start from index 1 whereas the library "ngx-datatable" pagination is 0 based.
Here's my current implementation:
mycomponent.html
<ngx-datatable
#usersTable
class='material text-centered'
[rows]='users'
[columns]="usersColumn"
[columnMode]="'force'"
[headerHeight]="50"
[footerHeight]="50"
[rowHeight]="'auto'"
[externalPaging]="true"
[offset]="page.offset"
[limit]="page.pageSize"
[count]="page.totalElements"
(page)='fetchList($event)'>
</ngx-datatable>
mycomponent.ts
page: any = {
offset: 0,
pageNumber: 1,
pageSize: 10,
totalElements: '',
sortBy: "id",
sortOrder: "desc"
};
ngOnInit() {
this.usersColumn = [
{
name: 'S.NO',
prop: 'sno'
},
{
name: 'First Name',
prop: 'firstName'
},
{
name: 'Last Name',
prop: 'lastName'
},
{
name: 'Email',
prop: 'email',
width: 200
},
{
name: 'Action',
cellTemplate: this.action
}
];
this.fetchList({ offset: 0 });
}
generateSerialNo(pageNo, size, i) {
const index = i + 1;
return pageNo == 1 ? index : (pageNo - 1) * size + index;
}
fetchList(pageInfo) {
this.page.pageNumber = pageInfo.offset + 1;
const { pageNumber, pageSize, sortBy, sortOrder } = this.page);
this.ListService.fetchList(pageNumber, pageSize, sortBy, sortOrder).subscribe(
success => {
if (success && !success['isError']) {
const responseObj = success['responseObject'];
if (responseObj) {
const List = responseObj.content || [];
const { totalElements } = responseObj;
this.users = List.map((item, i) => {
// set serial no. for user in current iteration
const serialNumber = this.generateSerialNo(this.page.pageNumber, this.page.pageSize, i);
return { sno: serialNumber, ...item };
});
this.page.totalElements = totalElements;
}
} else {
this.toastr.error(success['message'], 'Oops!');
}
},
errorResp => {
const error = errorResp['error'];
this.toastr.error(error['message'], 'Oops!');
}
);
Now Say, there's an action column in the table which consists of buttons to block or unblock user which on click calls a function as follows:
blockUnblockUser(toBlock: boolean) {
this.ListService.blockUnblockUser(toBlock, this.selectedUser.id).subscribe(
success => {
if (success && !success['isError']) {
this.fetchList(this.page);
this.utilService.closeModal();
this.toastr.success(success['message'], 'Success!');
} else {
this.utilService.closeModal();
this.toastr.error(success['message'], 'Oops!');
}
},
errorResp => {
const error = errorResp['error'];
this.utilService.closeModal();
this.toastr.error(error['message'], 'Oops!');
});
}
Here's the problem. On page load, I get my list for page number one and page number one is the active page. Now Click on page number 2, in the request param of API this is what goes:
list?pageNumber=2&pageSize=10&sortBy=id&sortOrder=desc
and in response, I get 3 data for page number 2 with 3 items.
Now if I click on the action button to either block or unblock particular user this is what sent in request params:
list?pageNumber=1&pageSize=10&sortBy=id&sortOrder=desc
and in response, I get data based on the page number 1 with 10 items.
but this time the active page in pagination is still "2"?
Please let me know where I am making mistake and how do I fix this. The backend team cannot make the pagination zero-based index for some reason.

Vue.js | Filters is not return

I have a problem.
I am posting a category id with http post. status is returning a data that is true. I want to return with the value count variable from the back. But count does not go back. Return in function does not work. the value in the function does not return from the outside.
category-index -> View
<td>{{category.id | count}}</td>
Controller File
/**
* #Access(admin=true)
* #Route(methods="POST")
* #Request({"id": "integer"}, csrf=true)
*/
public function countAction($id){
return ['status' => 'yes'];
}
Vue File
filters: {
count: function(data){
var count = '';
this.$http.post('/admin/api/dpnblog/category/count' , {id:data} , function(success){
count = success.status;
}).catch(function(error){
console.log('error')
})
return count;
}
}
But not working :(
Thank you guys.
Note: Since you're using <td> it implies that you have a whole table of these; you might want to consider getting them all at once to reduce the amount of back-end calls.
Filters are meant for simple in-place string modifications like formatting etc.
Consider using a method to fetch this instead.
template
<td>{{ categoryCount }}</td>
script
data() {
return {
categoryCount: ''
}
},
created() {
this.categoryCount = this.fetchCategoryCount()
},
methods: {
async fetchCategoryCount() {
try {
const response = await this.$http.post('/admin/api/dpnblog/category/count', {id: this.category.id})
return response.status;
} catch(error) {
console.error('error')
}
}
}
view
<td>{{count}}</td>
vue
data() {
return {
count: '',
}
},
mounted() {
// or in any other Controller, and set your id this function
this.countFunc()
},
methods: {
countFunc: function(data) {
this.$http
.post('/admin/api/dpnblog/category/count', { id: data }, function(
success,
) {
// update view
this.count = success.status
})
.catch(function(error) {
console.log('error')
})
},
},

How to pass an array values from one function to another function in vuejs?

I am trying to get the array values from
"validateBeforeSubmit" function to "saveForm" function. But I am
getting values of "undefined" in "arrlength". Please help me to solve.
This my code in vue.js
export default {
name: '',
data() {
return {}
},
ready: function() {
this.validateBeforeSubmit()
this.saveForm();
},
methods: {
validateBeforeSubmit() {
var fieldsVal = new Array();
var firstName = document.getElementById('firstName').value
var lastName = document.getElementById('lastName').value
var designation = document.getElementById('designation').value
if (firstName != "" && lastName != "" && designation != "") {
fieldsVal.push(firstName);
fieldsVal.push(lastName);
fieldsVal.push(designation);
return fieldsVal;
} else {
fieldsVal.length = 0;
return fieldsVal;
}
return fieldsVal;
},
saveForm() {
var fieldsValArray = this.validateBeforeSubmit();
var arrLength = fieldsValArray.length;
}
}
}
I can see multiple issues in your code:
1) Don't apply jQuery-like approach for getting input values. Use v-model instead. This will simplify your code
<template>
<input v-model="form.firstName" type="text"/>
</template>
<script>
export default {
data: {
form: {
firstName: '',
}
},
methods: {
validateBeforeSubmit() {
// take `firstName` directly from `data` not need for `getElementById`
const firstName = this.form.firstName;
}
},
}
</script>
2) Remove validateBeforeSubmit and saveForm from ready. Ready hook is obsolete in vue#2. And also it makes no sense. It's better to call it on form #submit.
3) It's better to create array using [] syntax instead of new Array()
Why never use new Array in Javascript
4) Always provide name for your component for easier debug
export default {
name: 'ValidationForm',
}
5) I don't know where was an issue but it works. Check this link below. I have updated your code. Try to submit form and check the console:
https://codesandbox.io/s/w6jl619qr5?expanddevtools=1&module=%2Fsrc%2Fcomponents%2FForm.vue

Why could not load data from Adapter into JSONStore?

function getListPhoneNumbers() {
var data = {listContacts:[{name:'Ho Cong Vi',number:'12345666'},{name:'hcv',number:'6543218'}]};
WL.Logger.info('Data:'+JSON.stringify(data));
return data;
}
function addListPhoneNumber(data) {
WL.Logger.debug('Add Data to JSONStore: ' + data);
return;
}
function updateListPhoneNumber(data) {
WL.Logger.debug('Updata Data from JSONStore: ' + data);
return;
}
function deleteListPhoneNumber(data) {
WL.Logger.debug('Delete Data from JSONStore: ' + data);
return;
}
This is my code in main.js:
$('#show-all-btn').on('click', showAllData);
var collectionName = 'Contacts',
collections = {};
collections[collectionName] = {
searchFields: {
name: 'string',
number: 'string'
},
adapter: {
name: 'listPhoneNumbers',
add: 'addListPhoneNumber',
replace: 'updateListPhoneNumber',
remove: 'deleteListPhoneNumber',
load: {
procedure: 'getListPhoneNumbers',
param: [],
key: 'listContacts'
}
}
};
WL.JSONStore.init(collections)
function showAllData() {
$('#show-all-btn').on("click", function() {
$('#info').show();
});
WL.JSONStore.get(collectionName).load().then(function(res) {
alert('ok' + JSON.stringify(res));
}).fail(function(errorObject) {
alert(errorObject);
});
}
This is the error:
[wl.jsonstore] {"src":"load","err":18,"msg":"FAILED_TO_LOAD_INITIAL_DATA_FROM_ADAPTER_INVALID_L‌​OAD_OBJ","col":"Contact","usr":"jsonstore","doc":{},"res":{}
The error message is saying the load object you passed is invalid. This is probably because you passed param instead of params. Notice the s at the end.
Also, this code:
WL.JSONStore.init(collections)
function showAllData() {
$('#show-all-btn').on("click", function() {
$('#info').show();
});
WL.JSONStore.get(collectionName).load().then(function(res) {
alert('ok' + JSON.stringify(res));
}).fail(function(errorObject) {
alert(errorObject);
});
}
Looks wrong, maybe what you meant to write is something like this:
WL.JSONStore.init(collections).then(function () {
WL.JSONStore.get(collectionName).count().then(function (numberOfDocsInCollection) {
if(numberOfDocsInCollection < 1) {
WL.JSONStore.get(collectionName).load().then(function(res) {
//handle success
})
}
})
});
I omitted handling failures for brevity. Note that the load will will duplicate items in the collection if those items already exist, hence the count to check if the collection is empty or not.