Get data in ag-grid - vue.js

I was able to pull data into the database with bootstrap-vue.
I need to transfer to ag-grid, but I don't know how to do it
Someone help-me, this is code in ag-grid:
<template v-if="instituicao">
<div>
<button #click="getSelectedRows()">Get Selected Rows</button>
<ag-grid-vue style="width: 1000px; height: 500px;"
class="ag-theme-balham"
v-model="instituicao.codigo" required
:floatingFilter="true"
:gridReady="onGridReady"
:enableColResize="true"
:columnDefs="columnDefs"
:rowData="rowData"
:enableSorting="true"
:enableFilter="true">
</ag-grid-vue>
</div>
</template>
<script>
import PageTitle from '../template/PageTitle'
import axios from 'axios'
import { baseApiUrl, showError } from '#/global'
import { AgGridVue } from "ag-grid-vue"
import { transformHeader, transformRows } from '../../lib/grid.js'
/* import "ag-grid-enterprise" */
export default {
name: 'InstituicaoAdmin',
components: { AgGridVue, PageTitle },
data() {
return {
columnDefs: null,
rowData: null,
mode: 'save',
instituicao: {},
instituicoes: [],
fields: [
{ key: 'id', label: 'Id', sortable: true },
{ key: 'name', label: 'Name', sortable: true }
],
}
},
methods: {
onGridReady(params) {
this.gridApi = params.api;
this.columnApi = params.columnApi;
this.gridApi.setHeaderHeight(50);
},
sizeToFit() {
this.gridApi.sizeColumnsToFit();
// this.autosizeHeaders();
},
autoSizeAll() {
var allColumnIds = [];
this.columnApi.getAllColumns().forEach(function(column) {
allColumnIds.push(column.colId);
});
this.columnApi.autoSizeColumns(allColumnIds);
},
getSelectedRows() {
const selectedNodes = this.gridApi.getSelectedNodes();
const selectedData = selectedNodes.map(node => node.data);
const selectedDataStringPresentation = selectedData.map(node => node.make + ' ' + node.model).join(', ');
alert(`Selected nodes: ${selectedDataStringPresentation}`);
},
loadInstituicoes() {
const url = `${baseApiUrl}/instituicao`
axios.get(url).then(res => {
this.instituicoes = res.data
})
},
reset() {
this.mode = 'save'
this.instituicao = {}
this.loadInstituicoes()
},
save() {
const method = this.instituicao.id ? 'put' : 'post'
const id = this.instituicao.id ? `/${this.instituicao.id}` : ''
axios[method](`${baseApiUrl}/instituicao${id}`, this.instituicao)
.then(() => {
this.$toasted.global.defaultSuccess()
this.reset()
})
.catch(showError)
},
remove() {
const id = this.instituicao.id
axios.delete(`${baseApiUrl}/instituicao/${id}`)
.then(() => {
this.$toasted.global.defaultSuccess()
this.reset()
})
.catch(showError)
},
loadInstituicao(instituicao, mode = 'save') {
this.mode = mode
this.instituicao = { ...instituicao }
}
},
beforeMount() {
this.columnDefs = [
{headerName: 'Id', field: 'id', sortable: true },
{headerName: 'Name', field: 'name', sortable: true, filter: true },
{headerName: 'Price', field: 'price', sortable: true, filter: true }
];
fetch('https://api.myjson.com/bins/15psn9')
.then(result => result.json())
.then(rowData => this.rowData = rowData);
},
computed: {
columnDefs() {
return transformHeader(this.payload.header);
},
rowData() {
return transformRows(this.payload.data.rows, this.columnDefs);
}
},
mounted() {
this.loadInstituicoes()
}
}
</script>
<style>
#import "../../../node_modules/ag-grid/dist/styles/ag-grid.css";
#import "../../../node_modules/ag-grid/dist/styles/ag-theme-balham.css";
</style>
My question is how can I do the GET, PUT, POST, and DELETE operations using the ag-grid framework.
Usando o bootstrap-vue, eu poderia executar ou obter o banco de dados através da propriedade "fields".
<script>
import PageTitle from '../template/PageTitle'
import axios from 'axios'
import { baseApiUrl, showError } from '#/global'
export default {
name: 'InstituicaoAdmin',
components: { PageTitle },
data: function() {
return {
mode: 'save',
instituicao: {},
instituicoes: [],
fields: [
{ key: 'id', label: 'Id', sortable: true },
{ key: 'name', label: 'Name', sortable: true }
]
}
},
methods: {
loadInstituicoes() {
const url = `${baseApiUrl}/instituicao`
axios.get(url).then(res => {
this.instituicoes = res.data
})
},
reset() {
this.mode = 'save'
this.instituicao = {}
this.loadInstituicoes()
},
save() {
const method = this.instituicao.id ? 'put' : 'post'
const id = this.instituicao.id ? `/${this.instituicao.id}` : ''
axios[method](`${baseApiUrl}/instituicao${id}`, this.instituicao)
.then(() => {
this.$toasted.global.defaultSuccess()
this.reset()
})
.catch(showError)
},
remove() {
const id = this.instituicao.id
axios.delete(`${baseApiUrl}/instituicao/${id}`)
.then(() => {
this.$toasted.global.defaultSuccess()
this.reset()
})
.catch(showError)
},
loadInstituicao(instituicao, mode = 'save') {
this.mode = mode
this.instituicao = { ...instituicao }
}
},
mounted() {
this.loadInstituicoes()
}
}
</script>

I was able to solve the problem using axios using destructuring:
beforeMount() {
this.columnDefs = [
{headerName: 'Id', field: 'id', editable: true},
{headerName: 'Name', field: 'name', editable: true}
];
axios.get(`${baseApiUrl}/instituicao`)
.then(({data}) => this.rowData = data)
},

Related

How do I seperate an array so the data shows up as individual list items?

I am struggling re-writing some older code I made in vue. I have a form which allows the user to enter multiple email recipients. The problem is that the array in which these emails are stored outputs them as one single item.
How do I seperate these email addresses?
This is my code. I know that Vue has something called Split, but I am not sure where I could use it here (or if it would change anything).
<template>
<b-form-group :label="label">
<vue-tags-input
v-model="inputValue"
:tags="tags"
:autocomplete-min-length="0"
:add-on-key="[',', 13]"
:autocomplete-items="filteredAutocompleteItems"
:placeholder="$t('addEmailAddressesHere')"
data-test-id="send-doc-email-to"
#before-adding-tag="addTag"
#tags-changed="tagsChanged"
class="mw-100"
/>
</b-form-group>
</template>
<script>
import {propertyService} from '#/services/property';
import {tenancyService} from '#/services/tenancy';
import {unitService} from '#/services/unit';
import {userService} from '#/services/user';
import VueTagsInput from '#johmun/vue-tags-input';
export default {
components: {
VueTagsInput
},
props: {
value: Array,
label: String,
entityId: String,
entityType: String,
prefill: {
type: Boolean,
default: false
},
asNotification: {
type: Boolean,
default: false
},
includeUser: {
type: Boolean,
default: false
}
},
data() {
return {
inputValue: '',
autocompleteItems: []
};
},
computed: {
tags() {
return (this.value || []).map(this.setText);
},
filteredAutocompleteItems() {
return this.autocompleteItems.filter(autocompleteItem =>
autocompleteItem.text.toUpperCase().includes(this.inputValue.toUpperCase()));
}
},
methods: {
addTag({tag, addTag}) {
if (!tag.recipients) {
tag.recipients = [{emailAddress: tag.text}];
}
addTag(tag);
},
setText(tag) {
tag.text = [tag.description, tag.recipients.map(recipient => recipient.emailAddress).join(', ')].filter(Boolean).join(' | ');
return tag;
},
tagsChanged(newTags) {
this.$emit('input', newTags);
},
load() {
switch (this.entityType) {
case 'TENANCY':
userService.getCurrentUser().then(userResult => {
tenancyService.getTenants(this.entityId).then(result => {
const defaultTags = [];
const recipients = result.data
.map(tenant => tenant.legalEntity)
.filter(legalEntity => legalEntity.email || (!legalEntity.email && this.asNotification ? legalEntity.name : null))
.map(legalEntity => ({
emailAddress: legalEntity.email || (!legalEntity.email && this.asNotification ? legalEntity.name.concat(' ', `(${this.$t('letterMail').toLowerCase()})`) : null),
legalEntityId: legalEntity.id
}));
if (recipients.length) {
defaultTags.push(this.setText({description: this.$t('tenants'), recipients}));
}
this.autocompleteItems.push(...defaultTags);
if (this.includeUser) {
defaultTags.push(this.setText({
description: this.$t('user'),
recipients: [{emailAddress: userResult.data.email}]
}));
}
if (this.prefill) {
this.tagsChanged(defaultTags);
}
tenancyService.getUnits(this.entityId).then(result =>
result.data.forEach(unitTenancy => this.addPropertyContactsToAutocompleteItems(unitTenancy.unit.propertyId)));
});
});
break;
case 'UNIT':
unitService.get(this.entityId).then(result =>
this.addPropertyContactsToAutocompleteItems(result.data.propertyId));
break;
case 'PROPERTY':
this.addPropertyContactsToAutocompleteItems(this.entityId);
break;
}
},
addPropertyContactsToAutocompleteItems(propertyId) {
propertyService.listContacts(propertyId).then(result => {
this.autocompleteItems.push(...result.data
.filter(contact => contact.email)
.map(contact => this.setText({
description: contact.profession ? this.$t(`model.contact.professions.${contact.profession}`) : null,
recipients: [{emailAddress: contact.email, legalEntityId: contact.id}]
}))
);
});
}
},
created() {
this.load();
}
};
</script>

why isnt vue-chartjs receiving data from api?

I don't understand my console log is printing all the data. Do i have to return the data to something for the data to update on the chart? Maybe its something with nuxt? I have tried async mounted and async fetch with the same result. I have tried putting a $ infront of this.$chartData.
<script>
import { Pie } from 'vue-chartjs/legacy'
import { Chart as ChartJS, Title, Tooltip, Legend, ArcElement, CategoryScale } from 'chart.js'
import EthplorerService from '../../services/EthplorerService'
import CoinGeckoService from '../../services/CoinGeckoService'
ChartJS.register(Title, Tooltip, Legend, ArcElement, CategoryScale)
export default {
name: 'PieChart',
components: {
Pie,
},
data() {
return {
chartData: {
labels: [],
datasets: [
{
data: [],
backgroundColor: ['#0074D9', '#FF4136', '#2ECC40', '#39CCCC', '#01FF70', '#85144b', '#F012BE', '#3D9970', '#111111', '#AAAAAA'],
},
],
},
chartOptions: {
responsive: true,
maintainAspectRatio: false,
},
}
},
async created() {
const limit = 10
try {
this.loading = true
const coinData = await CoinGeckoService.getCoinData('chainlink')
const contractAddress = coinData.data.platforms.ethereum
const { data } = await EthplorerService.getTopTokenHolders(contractAddress, limit)
console.log(data.holders.map((x) => x.address))
console.log(data.holders.map((x) => x.share))
this.chartData.labels = data.holders.map((x) => x.address)
this.chartData.datasets.data = data.holders.map((x) => x.share)
this.loading = false
return this.chartData
} catch (e) {
this.loading = false
console.log(e)
}
},
}
</script>
Turns out i was missing the array position [0]. And I was missing the v-if.
this.chartData.datasets[0].data = data.holders.map((x) => x.share)
Followed the examples here and here
<template>
<Pie
v-if="!loading"
:chart-options="chartOptions"
:chart-data="chartData"
:chart-id="chartId"
:dataset-id-key="datasetIdKey"
:plugins="plugins"
:css-classes="cssClasses"
:styles="styles"
:width="width"
:height="height"
/>
</template>
<script>
import { Pie } from 'vue-chartjs/legacy'
import { Chart as ChartJS, Title, Tooltip, Legend, ArcElement, CategoryScale } from 'chart.js'
import EthplorerService from '../../services/EthplorerService'
import CoinGeckoService from '../../services/CoinGeckoService'
ChartJS.register(Title, Tooltip, Legend, ArcElement, CategoryScale)
export default {
name: 'PieChart',
components: {
Pie,
},
props: {
chartId: {
type: String,
default: 'pie-chart',
},
datasetIdKey: {
type: String,
default: 'label',
},
width: {
type: Number,
default: 400,
},
height: {
type: Number,
default: 400,
},
cssClasses: {
default: '',
type: String,
},
styles: {
type: Object,
default: () => {},
},
plugins: {
type: Array,
default: () => [],
},
},
data() {
return {
loading: true,
chartData: {
labels: [],
datasets: [
{
data: [],
backgroundColor: ['#0074D9', '#FF4136', '#2ECC40', '#39CCCC', '#01FF70', '#85144b', '#F012BE', '#3D9970', '#111111', '#AAAAAA'],
},
],
},
chartOptions: {
responsive: true,
maintainAspectRatio: false,
},
}
},
async mounted() {
const limit = 10
try {
this.loading = true
const coinData = await CoinGeckoService.getCoinData('chainlink')
const contractAddress = coinData.data.platforms.ethereum
const { data } = await EthplorerService.getTopTokenHolders(contractAddress, limit)
console.log(data.holders.map((x) => x.address.slice(1, 5)))
console.log(data.holders.map((x) => x.share))
this.chartData.labels = data.holders.map((x) => x.address.slice(2, 7))
this.chartData.datasets[0].data = data.holders.map((x) => x.share)
this.loading = false
} catch (e) {
this.loading = false
console.log(e)
}
},
}
</script>

Vue + Vuetify + Axios + Django : CRUD data table

I am trying to build a Vuetify CRUD using AXIOS. I am able to do CRUD operations, but am not able to display the newly added data till the page is refreshed. When I select edit, I am not able to see the existing data while editing. The editable dialog box shows empty.
Please help me if to resolve this.
Here is my script
import Navbar from '../components/Navbar.vue'
import { getAPI } from '../axios-api'
// import DataService from "../services/DataService";
export default {
data: () => ({
dialog: false,
dialogDelete: false,
headers: [
{ text: 'ID', align: 'start', value: 'id',},
{ text: 'Length', value: 'size' },
{ text: 'Weight', value: 'weight' },
{ text: 'Actions', value: 'actions', sortable: false },
],
info: [],
editedIndex: -1,
editedItem: {
ID: '',
Weight: 0,
Length: 0,
},
defaultItem: {
name: '',
Weight: 0,
Length: 0,
},
}),
components:{
Navbar
},
computed: {
formTitle () {
return this.editedIndex === -1 ? 'New Item' : 'Edit Item'
},
},
methods: {
initialize () {
getAPI.get('calibration/sizeweight')
.then(response => {
this.info = response.data
})
},
editItem (item) {
this.editedIndex = this.info.indexOf(item)
this.editedItem = Object.assign({}, item)
this.dialog = true
},
deleteItem (item) {
this.editedIndex = this.info.indexOf(item)
this.editedItem = Object.assign({}, item)
this.dialogDelete = true
},
deleteItemConfirm () {
this.info.splice(this.editedIndex, 1)
this.closeDelete()
getAPI.delete('calibration/sizeweight/'+this.editedItem.id)
.then(response=>{
console.log(response)
})
},
close () {
this.dialog = false
this.$nextTick(() => {
this.editedItem = Object.assign({}, this.defaultItem)
this.editedIndex = -1
})
},
closeDelete () {
this.dialogDelete = false
this.$nextTick(() => {
this.editedItem = Object.assign({}, this.defaultItem)
this.editedIndex = -1
})
},
save () {
if (this.editedIndex > -1) {
Object.assign(this.info[this.editedIndex], this.editedItem)
getAPI.put('calibration/sizeweight/'+this.editedItem.ID,{id:this.editedItem.ID ,weight:this.editedItem.Weight,size:this.editedItem.Length})
.then(response=>{
console.log(response)
this.initialize()
})
} else {
this.info.push(this.editedItem)
getAPI.post('calibration/sizeweight',{id:this.editedItem.ID ,weight:this.editedItem.Weight,size:this.editedItem.Length})
.then(response=>{
console.log(response)
this.initialize()
})
.catch(error => { console.log(error.response.data)})
}
this.close()
},
},
watch: {
dialog (val) {
val || this.close()
},
dialogDelete (val) {
val || this.closeDelete()
},
},
created () {
this.initialize()
},
}
</script>

Vue Cant render data from axios inside datatable

i am trying to get data from axios and then render it in datable component
how you can see the hardcoded data is renderd every time , but i cant implement data from axios call,
i am loading same format data from axios and then try to update my hardocded rows but nothing happens, i am not shure thath i am doing it right way
can somone help
<template>
<div>
<mdb-datatable-2 v-model="data" />
</div>
</template>
<script>
import { mdbDatatable2 } from 'mdbvue';
export default {
name: 'Datatable',
components: {
mdbDatatable2
},
data() {
return {
data: {
columns: [
{
label: 'Account',
field: 'account',
sort: true
},
{
label: 'bt_mac',
field: 'bt_mac',
sort: true
},
{
label: 'rssi',
field: 'rssi',
sort: true
},
{
label: 'time_stamp',
field: 'time_stamp',
sort: true
}
],
rows: [{
account: 'Tiger Nixon',
bt_mac: 'System Architect',
rssi: 'Edinburgh',
time_stamp: '2011/04/25',
time: '2011/04/25'
},
{
account: 'Garrett Winters',
bt_mac: 'Accountant',
rssi: 'Tokyo',
time_stamp: '2018/04/25',
time: '2011/04/25'
},
{
account: 'Ashton Cox',
bt_mac: 'unior Technical Author',
rssi: 'San Francisco',
time_stamp: '2009/01/12',
time: '2011/04/25'
},]
}
}
},
methods: {
getSnomData () {
this.axios.get('http://172.27.11.174:1818/testJson').then((response) => {
console.log(this.data);
console.log(response.data.rows); this.rows = response.data;
console.log(this.data);
return response;
})
}
},
created() {
this.getSnomData();
}
,
mounted () {
this.getSnomData();
}
}
</script>
this.data.rows = response.data.data;
that helped in my case

Mutate object to use in MDbootstrap Vue

I am using MDBootstrap for Vue js, the way to use datatable is to to use prop :data="data" which I calling here tableData and I have columns ready but I need to mutate the rows inside my object,
I couldn't do that with rows:this.data or rows:data which is where I handle getting data from my server.
How can I handle this and mutate rows inside tableData ?
<template>
<div class="container-fluid">
<ProgressSpinner v-if="isLoading"/>
<mdb-datatable :data="tableData" striped bordered/>
</div>
</template>
<script>
import ProgressSpinner from './Preloader'
import DataTable from 'vue-materialize-datatable'
import { mdbDatatable } from 'mdbvue'
export default {
name: 'Companies',
data: () => ({
data: [],
tableData: {
columns: [
{ label: 'ID', field: 'id', sort: 'asc' },
{ label: 'Name', field: 'name' },
{ label: 'Phone', field: 'phone', sort: 'asc' },
{ label: 'Email', field: 'email', sort: 'asc' },
{ label: 'City', field: 'city', sort: 'asc' },
{ label: 'Join Date', field: 'joined_at' }
],
rows: []
},
}),
created() {
this.$store
.dispatch('allCompanies')
.then(() => {
this.data = this.$store.getters.getAllCompanies
})
.catch(() => {
this.customerErrors = this.$store.getters.customerError
})
},
computed: {
isLoading() {
return this.$store.getters.customersAreLoading
},
},
components: {
ProgressSpinner,
datatable: DataTable,
mdbDatatable
},
mounted() {
$('.container-fluid').bootstrapMaterialDesign()
}
}
</script>
You should assign the value to tableData.rows when available.
this.$store
.dispatch('allCompanies')
.then(() => {
this.tableData.rows = this.$store.getters.getAllCompanies
})