How to loop inside map function using jsx format React JS - react-redux

I need help in rendering my array I want to make a condition inside my map function. But somehow my transpiler is not the accepting and having parsing error
Here is my code:
import { getGroups } from '../../actions/groupActions'
import { refreshToken } from '../../actions/authActions'
import { connect } from 'react-redux'
import _ from 'lodash'
import { Link } from "react-router"
class Group extends React.Component {
constructor(props) {
super(props);
this.state = {
groups: []
};
}
componentWillMount(){
this.props.getGroups().then(() => {
console.log('this groups props: ', this.props)
if(this.props.errors.code === 'UNAUTHORIZED'){
this.props.refreshToken().then(() => {
this.props.getGroups()
})
}
})
}
render(){
const groupArr = _.valuesIn(this.props.groups)
return (
<div>
<h1>Groups</h1>
<table className="table table-responsive table-bordered table-condensed">
<thead>
<tr>
<td>Name</td>
<td>Queue</td>
<td>Created At</td>
<td>Execution Type</td>
<td>Members</td>
<td>Action</td>
</tr>
</thead>
<tbody>
{this.props.groups ? (groupArr.map((groups, i) => {
return (
<tr key={i}>
<td>{groups.name}</td>
<td>{groups.queue}</td>
<td>{groups.createdAt}</td>
<td>{groups.executionType}</td>
<td>
{groups.members ? (groups.members.map((members, index) => {
{members.type === 'command' ? (
return (<div className="alert alert-success" role="alert" key={index}>{members._id}</div>)
) : (
return (<div className="alert alert-danger" role="alert" key={index}>{members._id}</div>)
) }
})) : (return ('No members found'))}
</td>
<td>
<Link className="btn btn-sm btn-warning" >
<i className="fa fa-pencil"></i>
</Link>
<button className="btn btn-sm btn-danger">
<i className="fa fa-trash-o"></i>
</button>
<button className="btn btn-sm btn-success">
<i className="fa fa-play-circle"></i>
</button>
</td>
</tr>
)
})) : (<tr>No records found</tr>)}
</tbody>
</table>
</div>
);
}
}
Group.propTypes = {
getGroups: React.PropTypes.func.isRequired,
errors: React.PropTypes.object.isRequired,
refreshToken: React.PropTypes.func
}
Group.contextTypes = {
router: React.PropTypes.object.isRequired
}
function mapStateToProps(state) {
return{
groups: state.groupReducer.groups,
links: state.groupReducer.links,
errors: state.groupReducer.errors
}
}
export default connect(mapStateToProps, { getGroups, refreshToken })(Group)
Here is the error:
SyntaxError: C:/Users/Frank/Projects/crun_fe/src/js/react/components/group/Group.js: Unexpected token (55:26)
53 | {groups.members ? (groups.members.map((members, index) => {
54 | {members.type === 'command' ? (
> 55 | return ({members._id})
| ^
56 | ) : (
57 | return ({members._id})
58 | ) }

You are using the ternary operator in a wrong way, Syntax is:
condition ? expression : expression
Both values should be expression but you are using return statement, that's why it is throwing the error.
If you want to return the result then use it in this way:
return a ? a+1 : 0;
Didn't run this code, just made some changes to solve your original problem, please check the proper closing of braces and tags, Try this:
{
this.props.groups ? groupArr.map((groups, i) => {
return (
<tr key={i}>
.....
<td>
{
groups.members ?
groups.members.map((members, index) => {
return members.type === 'command' ?
<div className="alert alert-success" role="alert" key={index}>{members._id}</div>
:
<div className="alert alert-danger" role="alert" key={index}>{members._id}</div>
})
: <div>'No members found'</div>
}
</td>
.....
</tr>
)
}) : <tr> No records found </tr>
}

Related

Datatable data in vuejs and laravel is not showing on mobile

I am working with laravel and vuejs I show the data with dataTable, in the mobile version it does not show me the api data, the problem is in the mobile version that is not shown, in the desktop version if the data is shown, the edit buttons do not open in mobile version either. I have tried link an api from the internet and if it shows me the data.
Controller:
<?php
namespace App\Http\Controllers\Admin;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use App\Models\Admin\Dependence;
use App\Http\Controllers\Controller;
use App\Http\Controllers\ResponseApiController;
class DependenceController extends ResponseApiController
{
public function getDependencies()
{
$dependencies = Dependence::orderBy('created_at', 'desc')->get();
$message = $this->sendResponse($dependencies, 'Dependencias listadas correctamente');
return $message;
}
}
Route:
Route::get('dependencies', 'Admin\DependenceController#getDependencies');
Vue - Libraries in global file:
//DataTables
import 'datatables.net-bs4';
import 'datatables.net/js/jquery.dataTables.min.js';
import 'datatables.net-bs4/css/dataTables.bootstrap4.min.css';
import 'datatables.net-bs4/js/dataTables.bootstrap4.min.js';
import 'datatables.net-responsive-bs4/css/responsive.bootstrap4.min.css';
import 'datatables.net-responsive-bs4/js/responsive.bootstrap4.min.js';
//DataTable Global
Vue.prototype.$tableGlobal = function(table) {
this.$nextTick(() => {
$(table).DataTable();
});
}
Template:
<template>
<div class="container-fluid">
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-header">
<div class="row">
<div class="col-auto mr-auto">
<h2 class="text-secondary">Dependencies List</h2>
</div>
<div class="col-auto">
<button class="right btn btn-primary btn-sm" v-b-modal.modal-1 #click="showModal = true">Add</button>
</div>
</div>
</div>
<!-- /.card-header -->
<div class="card-body animated fadeIn">
<table id="tblDependencies" class="table table-bordered table-hover dt-responsive">
<thead>
<tr>
<th>Description</th>
<th>Options</th>
</tr>
</thead>
<tbody>
<tr v-for="dependence in dependencies" :key="dependence.id">
<td>{{ dependence.description }}</td>
<td>
<!-- Change Status -->
<b-button size="sm" #click="statusUpdate(dependence)" class="mr-1" :class="[dependence.status == 1 ? 'btn-success' : 'btn-danger']">
<b-icon :icon="dependence.status == 1 ? 'check' : 'x' "></b-icon>
</b-button>
<!-- Edit -->
<b-button v-b-modal.editDependence size="sm" #click="editDependence(dependence)" class="btn btn-warning">
<b-icon icon="pencil-fill"></b-icon>
</b-button>
</td>
</tr>
</tbody>
</table>
</div>
<!-- /.card-body -->
</div>
<!-- /.card -->
</div>
<!-- /.col -->
</div>
<AddDependence ref="dependenceModal" #reload="getDependencies"></AddDependence>
<EditDependence ref="editModal" :editDependence="this.dataEditDependence" #reload="getDependencies"></EditDependence>
</div>
</template>
<script>
// Services
import * as dependenceService from '../../services/dependence';
// Components
import AddDependence from '../../components/Admin/Dependence/AddDependence.vue';
import EditDependence from '../../components/Admin/Dependence/EditDependence.vue'
export default {
data() {
return {
dependencies: [],
dataEditDependence: {}
}
},
mounted() {
this.getDependencies();
},
components: {
AddDependence,
EditDependence
},
methods: {
getDependencies: async function() {
try {
const response = await dependenceService.getDependencies();
if(response.status == 200) {
this.dependencies = response.data.data;
this.reloadTable();
}
} catch (error) {
this.loading = false
console.log(error);
if (error.response.status == 422){
console.log(error);
}
}
},
statusUpdate: async function(dependence) {
try {
const response = await dependenceService.activateDesactivate(dependence.id);
if (response.status == 200) {
if(response.data.data.status == 1) {
dependence.status = 1;
}else {
dependence.status = 0;
}
this.$alerta('Actualizado', 'Estado actualizado correctamente', 'success');
this.reloadTable();
}
} catch (error) {
console.log(error);
}
},
editDependence(dependence) {
this.dataEditDependence = dependence;
},
reloadTable() {
$('#tblDependencies').DataTable().destroy();
this.$tableGlobal('#tblDependencies');
},
}
}
</script>
http_service:
import store from '../store';
import axios from 'axios';
export function http() {
return axios.create({
baseURL: store.state.apiURL,
});
}
Service:
import {http} from './http_service';
export function getDependencies() {
return http().get('/dependencies');
}

Laravel + Vue V-IF updating in the database but not in the view

I have a project when I'm using Laravel 7.3 + Vue.
I am trying to assign a company to an internal employee. When I click the "Assign Company" button everything is fine and I can select the company in a select box, but when I click the "Save Company" button now, I can see the change in my database, but I don not see the changes live in my view/template, I need to refresh the webpage to see the assigned company.
This is my File.vue between the <template>:
<td><h4 v-if="editEmpleado" class="text-black-50">{{EmpleadosInterno.empresa}}</h4>
<select v-else class="form-control" id="Cliente" v-model="ClienteSeleccionado">
<option v-for="Cliente in Clientes"
:key="Cliente.id"
:value="Cliente">{{Cliente.nombreempresa}}</option>
</select>
</td>
<td>
<a v-if="editEmpleado" type="button" class="btn btn-primary" v-on:click="onClickEdit()">
Assign Company
</a>
<button v-else type="button" class="btn btn-success" v-on:click="onClickUpdate()">
Save Company
</button>
</td>
And this is my script
export default {
props: ['EmpleadosInterno'],
data() {
return {
ClienteSeleccionado: {},
Clientes: [],
csrf: document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
editEmpleado: true
}
},
mounted() {
axios.get('/Clientes').then((response) => {
this.Clientes = response.data;
},
);
},
methods: {
onClickEdit() {
this.editEmpleado = false;
},
onClickUpdate() {
const params = {
nombreempresa: this.ClienteSeleccionado.nombreempresa
}
axios.put(`/EmpleadosInternos/${this.EmpleadosInterno.id}`, params).then((response) => {
const EmpleadosInterno = response.data;
this.$emit('update', EmpleadosInterno);
this.editEmpleado = true;
});
},
This is my services.vue
<div class="container">
<div class="row justify-content-center text-center">
<div class="col-md-12">
<h2 class="text-primary">Empleados Registrados:</h2>
<table class="table table-bordred table-striped ">
<thead>
<tr>
<th>Nombre</th>
<th>Telefono</th>
<th>Empresa</th>
<th>Acción</th>
</tr>
</thead>
<tbody>
<empleadocomponente-component
v-for="(EmpleadosInterno, index) in EmpleadosInternos"
:key="EmpleadosInterno.id"
:EmpleadosInterno="EmpleadosInterno"
#update="updateEmpleadosInterno(index, ...arguments)"
#delete="deleteEmpleadosInterno(index)">
</empleadocomponente-component>
</tbody>
</table>
</div>
</div>
</div>
<script>
export default {
data(){
return {
EmpleadosInternos: [],
}
},
mounted() {
axios.get('/EmpleadosInternos').then((response) => {
this.EmpleadosInternos = response.data;
},
);
},
methods: {
updateEmpleadosInterno(index, EmpleadosInterno){
this.EmpleadosInternos[index] = EmpleadosInterno;
},
deleteEmpleadosInterno(index){
this.EmpleadosInternos.splice(index, 1);
}
}
}
</script>

React -Redux: How to pass the text box value as an argument to dispatch method while dispatching the action on submit event

please advise how to pass the input value to the dispatch method.I want to pass the policy number to the action method in index.js which is in action folder.The retrievepolicy method need to get the policy number as an argument
On submit event,the retrievepolicy method will be dispatched
import React from 'react'
import { connect } from 'react-redux'
import { sayHello } from '../actions'
import { retrievePolicy } from '../actions'
class Button extends React.Component {
constructor(props) {
super(props);
this.state = {
policyNumber: ""
}
this.handleChange = this.handleChange.bind(this);
}
render() {
const { saySomething, retrievePolicy, whatsUp } = this.props;
return (
<div class="container">
<div class="text-white bg-dark" >
<button class="btn btn-info" onClick={saySomething}>PRESS TO DISPATCH
FIRST ACTION</button>
<h2>{whatsUp}</h2>
<table>
<tr>
<td><label for="exampleInputEmail" class="label">Policy Number</label>
</td>
<td><input type="textbox" class="textarea" id="policyNumberid"
name="policyNumberid"
value={this.state.policyNumber} onChange={this.handleChange}
/></td>
</tr>
<tr>
<td>Data Location</td>
<select class="form-control" id="timezone" name="timezone"
selected="selected" >
<option value="" selected disabled hidden>Choose here</option>
<option value="Test">\\w</option>
<option value="Stage">\\ws</option>
</select>
</tr>
<tr><button class="btn btn-info" onClick={retrievePolicy} >Retrieve
Policy Information</button></tr>
</table>
</div>
</div>
)
}
handleChange(typedText) {
alert('hi')
this.setState({ policyNumber: typedText.target.value }, () => {
console.log(this.state.policyNumber);
});
}
};
const mapStateToProps = (state) => ({
whatsUp: state.policy,
stateObject: state
})
const mapDispatchToProps = (dispatch) => (
{
saySomething: () => { dispatch(sayHello()) },
retrievePolicy: (policyNumber) => {
dispatch(retrievePolicy(policyNumber)) }
}
)
Button = connect(mapStateToProps, mapDispatchToProps)(Button)
export default Button

How to pass updated data to already child vue component rendered

I'm trying to update some vars into a component from parent. My situation is this:
I have a parent component:
import LugarListComponent from './LugarListComponent';
import LugarAddComponent from './LugarAddComponent'
export default {
components:{
'lugar-list-component' : LugarListComponent,
'lugar-add-component' : LugarAddComponent,
},
data(){
return {
show: false,
nombre: '',
desc : '',
}
},
methods:{
showComponent: function () {
this.show = true;
},
hideComponent: function () {
this.show = false;
},
setLugar: function(lugar){
this.show = true;
}
},
mounted() {
//console.log('Component mounted.')
}
}
<template>
<div class="container">
<h3>Lugares</h3>
<div style="text-align: right">
<button type="button" class="btn btn-primary" v-show="!show" v-on:click.prevent="showComponent"><i class="fa fa-plus"></i> Adicionar</button>
<button type="button" class="btn btn-success" v-show="show" v-on:click.prevent="hideComponent"><i class="fa fa-arrow-left"></i> Regresar</button>
</div>
<br>
<lugar-list-component v-show="!show" #setLugar="setLugar"></lugar-list-component>
<lugar-add-component v-show="show" #hideComponent="hideComponent"></lugar-add-component>
</div>
</template>
This component has two childs components, lugar-list for list places and lugar-add for add a place. I have a show var for control when I show one of this.
I want to edit a place, but I want to send data to lugar-add for show his values into this component, but I don't find any solution for update the vars into lugar-add. Here I show the code of this components.
For lugar-add
export default {
data(){
return {
image: '',
nombre: '',
desc : ''
}
},
methods: {
onImageChange(e) {
let files = e.target.files || e.dataTransfer.files;
if (!files.length)
return;
this.createImage(files[0]);
},
createImage(file) {
let reader = new FileReader();
let vm = this;
reader.onload = (e) => {
vm.image = e.target.result;
};
reader.readAsDataURL(file);
},
uploadImage(){
axios.post('/lugar',{
image: this.image,
nombre: this.nombre,
desc: this.desc
}).then(response => {
if(response.status == 200){
this.$emit('hideComponent')
}
});
},
setAttributes(lugarEdit){
console.log('disparado');
this.nombre = lugarEdit.nombre;
this.desc = lugarEdit.desc;
}
},
mounted() {
//console.log('Component mounted.');
this.$on(
'setAttributes',
function(lugar) {
this.nombre = lugar.nombre;
this.desc = lugar.desc;
}
);
}
<template>
<div class="container">
<div class="form-group">
<label>Nombre</label>
<input type="text" v-model="nombre" class="form-control" placeholder="Nombre del lugar">
</div>
<div class="form-group">
<label for="descTexArea">Descripción</label>
<textarea v-model="desc" class="form-control" id="descTexArea" rows="3"></textarea>
</div>
<div class="form-group">
<label for="exampleFormControlFile1">Subir imágenes</label>
<input type="file" v-on:change="onImageChange" class="form-control-file" id="exampleFormControlFile1">
</div>
<div class="form-group">
<button type="button" class="btn btn-primary" #click="uploadImage">Adicionar</button>
</div>
<div class="col-md-3" v-if="image">
<img :src="image" class="img-responsive" height="70" width="90">
</div>
</div>
</template>
Here I use event for hide this component and show the lugar-list component. Here is the code for lugar-list
export default {
name: 'lugar-list-component',
data:function(){
return {
listLugares : [],
id : '',
}
},
methods:{
getLugares: function () {
fetch('/lugar')
.then(response => response.json())
.then(res => {
this.listLugares = res;
})
},
setId: function(id){
this.id = id;
},
removeLugar: function(id){
this.id = id;
axios.delete('lugar/'+id)
.then(response => {
this.getLugares();
});
},
editLugar: function(id){
this.id = id;
axios.get('lugar/'+id)
.then(response => {
this.$emit('setLugar',response);
});
},
},
mounted() {
this.getLugares();
}
}
<template>
<div class="container">
<table class="table table-striped">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Nombre</th>
<th scope="col">Desc.</th>
<th scope="col">Fecha</th>
<th scope="col">Acciones</th>
</tr>
</thead>
<tbody>
<tr v-for="(item, index) in listLugares">
<th scope="row">{{ index+1 }}</th>
<td>{{ item.nombre }}</td>
<td>{{ item.desc }}</td>
<td>{{ item.created_at }}</td>
<td>
<button type="button" class="btn btn-success" v-on:click.prevent="editLugar(item.id)"><i class="fa fa-edit"></i> Editar</button>
<button type="button" class="btn btn-danger" v-on:click.prevent="removeLugar(item.id)"><i class="fa fa-remove"></i> Eliminar</button>
</td>
</tr>
</tbody>
</table>
</div>
</template>
I hope that you can understand me. Thanks.
Emit an event from the 1st child component to update parent's prop. Then pass the value you want to update as a prop to the secund child element.
I don't find other solution that use routes with params, I believe that is the best solution.
Here is my routes
{
path: '/lugar', component: require('./components/lugar/LugarComponent').default,
children: [
{ path: '', component: LugarList },
{
path: 'add/:id?',
name: 'lugarAdd',
component: LugarAdd
},
{
path: 'list',
component: LugarList
}
]
}
The route for Add a place has an optional param.
Now, into the Add component I get the param with this code:
this.id = this.$route.params.id;
this.modeEdit = true;
axios.get('/lugar/'+this.id)
.then(response => {
this.nombre = response.data.nombre;
this.desc = response.data.desc;
for(let i = 0; i<response.data.images.length; i++){
this.image.push(response.data.images[i]);
}
});
When I get the place id I request for its information with axios.

How to sort only the displayed items in table with vue

I have two questions regarding the following code.
1st problem: say I have four items in the array with ids of [1,2,4,5,7]
If I click on the sort and i have 2 items per page chosen then it will show me entries with id's of 1&2 or 5&7 as I toggle the reverse order.
So how can I get the table to just sort the items that are displayed in the paginated view?
2nd problem:
We are using a mixture of vue and some jquery from an admin template we purchased, But where it has <div class="checkbox checkbox-styled"> written in the code the check boxes will not render unless I put the Vue code in a setTimeout with an interval val of '100' or more.
And it generally just doesn't render stuff in jquery well if the item that relies on jquery is in a vue for loop.
Has anyone got an explanation for this?
Please note I've deleted as much out of this to keep the question as small as possible.
<div class="section-body">
<!-- BEGIN DATA TABLE START -->
<form class="form" role="form">
<div class="row">
<div class="col-lg-12">
<div id="" class="dataTables_wrapper no-footer">
<div class="table-responsive">
<table style="width: 100%" cellpadding="3">
<tr>
<td>
<div class="dataTables_length" id="entries_per_page">
<label>
<select name="entries_per_page" aria-controls="datatable" v-model="itemsPerPage">
<option value='2'>2</option>
<option value='20'>20</option>
<option value='30'>30</option>
</select>
entries per page
</label>
</div>
</td>
</tr>
</table>
<table class="table table-striped table-hover dataTable">
<thead>
<tr>
<th>
<div class="checkbox checkbox-styled">
<label>
<input type="checkbox" v-model="selectAll" :checked="allSelected" #click="selectAllCheckboxes">
</label>
</div>
</th>
<th v-bind:class="{'sorting': col.key !== sortKey, 'sorting_desc': col.key == sortKey && !isReversed, 'sorting_asc': col.key == sortKey && isReversed}" v-for="col in columns" #click.prevent="sort(col.key)">
<a href="#" v-cloak>${ col.label | capitalize}</a>
</th>
<th class="text-right">Actions</th>
</tr>
</thead>
<tbody>
<tr v-for="item in items | paginate | filterBy search">
<td width="57">
<div class="checkbox checkbox-styled">
<label>
<input type="checkbox" value="${ item.id }" v-model="cbIds" :checked="cbIds.indexOf(item.id) >= 0" />
</label>
</div>
</td>
<!-- !ENTITY_NAME TABLE COLUMNS START -->
<td v-cloak>${ item.id }</td>
<td v-cloak>${ item.title }</td>
<!-- !ENTITY_NAME TABLE COLUMNS END -->
<td class="text-right">
<button type="button" class="btn btn-icon-toggle" data-toggle="tooltip" data-placement="top" data-original-title="Edit row" #click="editItem(item)">
<i class="fa fa-pencil"></i></button>
<button type="button" class="btn btn-icon-toggle" data-toggle="tooltip" data-placement="top" data-original-title="Delete row" #click="deleteModalOpened(item)">
<i class="fa fa-trash-o"></i>
</button>
</td>
</tr>
</tbody>
</table>
<!-- PAGINATION START -->
<div class="dataTables_info" role="status" aria-live="polite" v-if="resultCount > 0" v-cloak>
Showing ${ currentCountFrom } to ${ currentCountTo } of ${ resultCount } entries
</div>
<div class="dataTables_paginate paging_simple_numbers" id="datatable_paginate" v-if="resultCount > 0">
<a class="paginate_button previous disabled" #click="previousPage()" v-if="currentPage==0">
<i class="fa fa-angle-left"></i>
</a>
<a class="paginate_button previous" #click="previousPage()" v-else>
<i class="fa fa-angle-left"></i>
</a>
<span v-for="pageNumber in totalPages">
<a class="paginate_button current" #click="setPage(pageNumber)" v-show="pageNumber == currentPage" v-cloak>${ pageNumber + 1 }</a>
<a class="paginate_button" #click="setPage(pageNumber)" v-show="pageNumber != currentPage" v-cloak>${ pageNumber + 1 }</a>
</span>
<a class="paginate_button next disabled" #click="nextPage()" v-if="currentPage == (totalPages - 1)">
<i class="fa fa-angle-right"></i>
</a>
<a class="paginate_button previous" #click="nextPage()" v-else>
<i class="fa fa-angle-right"></i>
</a>
</div>
<!-- PAGINATION END -->
</div>
</div>
</div>
</div>
</form>
<!-- BEGIN DATA TABLE END -->
</div>
<script>
Vue.config.delimiters = ['${', '}'];
new Vue({
el: '#app',
data: {
items: [],
columns: [
{
key: 'id' ,
label: 'id' ,
},
{
key: 'title' ,
label: 'title' ,
},
],
// ALL PAGINATION VARS
currentPage: 0,
itemsPerPage: 20,
resultCount: 0,
totalPages: 0,
currentCountFrom: 0,
currentCountTo: 0,
allSelected: false,
cbIds: [],
sortKey: '',
isReversed: false
},
computed: {
totalPages: function() {
return Math.ceil(this.resultCount / this.itemsPerPage);
},
currentCountFrom: function () {
return this.itemsPerPage * this.currentPage + 1;
},
currentCountTo: function () {
var to = (this.itemsPerPage * this.currentPage) + this.itemsPerPage;
return to > this.resultCount ? this.resultCount : to;
}
},
ready: function() {
this.pageUrl = '{{ path('items_ajax_list') }}';
this.getVueItems();
},
filters: {
paginate: function(list) {
this.resultCount = this.items.length;
if (this.currentPage >= this.totalPages) {
this.currentPage = Math.max(0, this.totalPages - 1);
}
var index = this.currentPage * this.itemsPerPage;
return this.items.slice(index, index + this.itemsPerPage);
}
},
methods : {
sort: function (column) {
if (column !== this.sortKey) {
this.sortKey = column;
this.items.sort(this.sortAlphaNum);
this.isReversed = false;
return;
}
this.reverse();
if (this.isReversed) {
this.isReversed = false;
}
else {
this.isReversed = true;
}
},
reverse: function () {this.items.reverse()},
sortAlphaNum: function (a, b) {
if (a[this.sortKey] === undefined) return;
if (b[this.sortKey] === undefined) return;
var cva = a[this.sortKey].toString().toLowerCase();
var cvb = b[this.sortKey].toString().toLowerCase();
var reA = /[^a-zA-Z]/g;
var reN = /[^0-9]/g;
var aA = cva.replace(reA, "");
var bA = cvb.replace(reA, "");
if(aA === bA) {
var aN = parseInt(cva.replace(reN, ""), 10);
var bN = parseInt(cvb.replace(reN, ""), 10);
return aN === bN ? 0 : aN > bN ? 1 : -1;
}
return aA > bA ? 1 : -1;
},
setPage: function(pageNumber) {this.currentPage = pageNumber},
nextPage: function () {
if (this.pageNumber + 1 >= this.currentPage) return;
this.setPage(this.currentPage + 1);
},
previousPage: function () {
if (this.currentPage == 0) return;
this.setPage(this.currentPage - 1);
},
getVueItems: function(page){
this.$http.get(this.pageUrl)
.then((response) => {
var res = JSON.parse(response.data);
this.$set('items', res);
});
},
}
});
</script>
Regarding your first problem, You can break the bigger array in smaller arrays, than show those on paginated way and sort the smaller array, I have created a fiddle to demo it here.
Following is code to break it in smaller arrays:
computed: {
chunks () {
var size = 2, smallarray = [];
for (var i= 0; i<this.data.length; i+=size) {
smallarray.push(this.data.slice(i,i+size))
}
return smallarray
}
}
Regarding your second problem, if the issue is that items is not getting properly populated after this.$http.get call, it can be due to wrong scope of this variable as well, which can be corrected like following:
getVueItems: function(page){
var self = this
this.$http.get(this.pageUrl)
.then((response) => {
var res = JSON.parse(response.data);
self.items = res;
});
},

Resources