Vue + Vuetify + Axios + Django : CRUD data table - vue.js

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>

Related

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>

vuejs store localStorage set object

I have a theme config store, and I set "localStorage" on this store, I can read it the same way. but I'm recording them one by one, is it possible to send them all as objects instead, if possible, please give an example.
how do i set it on the store
I'm a little newbie in storage, please comment accordingly.
export const $themeConfig = {
app: {
appName: 'Name',
appLogoImage: '',
},
layout: {
skin: 'light',
type: 'vertical',
contentWidth: 'full',
menu: {
hidden: false,
isCollapsed: false,
},
navbar: {
type: 'floating',
backgroundColor: 'dark',
},
footer: {
type: 'static',
},
customizer: true,
},
}
import {$themeConfig} from '../../themeConfig'
export default {
namespaced: true,
state: {
layout: {
skin: localStorage.getItem('themeConfig-skin') || $themeConfig.layout.skin,
type: localStorage.getItem('themeConfig-menuLayout') || $themeConfig.layout.type,
contentWidth: localStorage.getItem('themeConfig-contentWidth') || $themeConfig.layout.contentWidth,
menu: {
hidden: localStorage.getItem('themeConfig-menuHidden') || $themeConfig.layout.menu.hidden,
},
navbar: {
type: localStorage.getItem('themeConfig-navbarType') || $themeConfig.layout.navbar.type,
backgroundColor: localStorage.getItem('themeConfig-navbarBG') || $themeConfig.layout.navbar.backgroundColor,
},
footer: {
type: localStorage.getItem('themeConfig-footerType') || $themeConfig.layout.footer.type,
},
},
},
getters: {},
mutations: {
UPDATE_SKIN(state, skin) {
state.layout.skin = skin
localStorage.setItem('themeConfig-skin', skin)
if (skin === 'dark') document.body.classList.add('dark-layout')
else if (document.body.className.match('dark-layout')) document.body.classList.remove('dark-layout')
},
UPDATE_LAYOUT_TYPE(state, val) {
localStorage.setItem('themeConfig-menuLayout', val)
state.layout.type = val
},
UPDATE_CONTENT_WIDTH(state, val) {
localStorage.setItem('themeConfig-contentWidth', val)
state.layout.contentWidth = val
},
UPDATE_NAV_MENU_HIDDEN(state, val) {
localStorage.setItem('themeConfig-menuHidden', val)
state.layout.menu.hidden = val
},
UPDATE_NAVBAR_CONFIG(state, obj) {
if (obj.backgroundColor)
localStorage.setItem('themeConfig-navbarBG', obj.backgroundColor)
else
localStorage.setItem('themeConfig-navbarType', obj.type)
Object.assign(state.layout.navbar, obj)
},
UPDATE_FOOTER_CONFIG(state, obj) {
if (obj.type)
localStorage.setItem('themeConfig-footerType', obj.type)
else
localStorage.setItem('themeConfig-footerType', obj.type)
Object.assign(state.layout.footer, obj)
},
},
actions: {},
}
You can create helper functions like:
function updateThemeConfig (key, data) {
let state = localStorage.getItem('themeConfig');
if(state){
state = JSON.parse(state);
state[key] = data;
} else {
state = {
[key]: data;
}
}
localStorage.setItem('themeConfig', JSON.stringify(state))
}
function getThemeConfig (key) {
let state = localStorage.getItem('themeConfig');
if(state) {
state = JSON.parse(state);
return state[key];
}
return;
}
Then use it like this:
footer: {
type: getThemeConfig('footerType') || $themeConfig.layout.footer.type,
},
...
UPDATE_LAYOUT_TYPE(state, val) {
updateThemeConfig('menuLayout', val);
state.layout.type = val
},

VueX and axios posting previous data along with data from new request

I have a postAsset action in my vuex store like so
async postAsset({dispatch}, asset) {
const f = await dispatch('srcToFile', asset);
asset[0].files.fileList = f;
const fileData = asset[0].files.fileList;
const detailData = asset[0].detail;
const fData = new FormData();
fData.append('Name', asset[0].name);
Object.keys(detailData).forEach((key) => {
fData.append(`Detail.${key}`, detailData[key]);
});
for (var i = 0; i < fileData.length; i++) {
fData.append('Files', fileData[i]);
}
await axios({
method: 'post',
url: 'https://localhost:5001/api/Assets',
data: fData,
headers: {
'Content-Type': undefined
}
})
.then(function(response) {
console.warn(response);
})
.catch(function(response) {
console.warn(response);
});
}
It is successfully posting to my api backend and to the database.
The issue that I am running into is that after I make the first post it posts the previous data and the new data I do not know why it is doing this. I did add await to the axios call but that just slowed it down it is still posting two times after the first and im sure if i keep posting it will continue to post the previous ones into the db again and again. Im at a loss as to what is going on so reaching out for some assistance to see if I can get this resolved.
examples of what it looks like in the db
does anyone have any advice for me so I can get this fixed? I should only be getting one item posted at a time that is the desired result. I have gone through my inputs and put in .prevent to stop them from clicking twice but I don't think it is that .. this is like it is saving the data and reposting it all at once each time I add a new record .
UPDATE:
the code that calls the action
populateAssets ({ dispatch }, asset) {
return new Promise((resolve) => {
assets.forEach((asset) => {
commit('createAsset', asset);
);
dispatch('postAsset', asset);
resolve(true);
});
},
the populate assets populates a list with a completed asset.
and asset is coming from the srcToFile method
that converts the files to a blob that I can post with
async srcToFile(context, asset) {
const files = asset[0].files.fileList;
let pmsArray = [];
for (let f = 0; f < files.length; f++) {
var data = files[f].data;
let name = files[f].name;
let mimeType = files[f].type;
await fetch(data)
.then(function(res) {
const r = res.arrayBuffer();
console.warn('resource ', r);
return r;
})
.then(function(buf) {
console.warn('buffer: ', [buf]);
let file = new File([buf], name, { type: mimeType });
pmsArray.push(file);
});
}
console.warn(pmsArray);
return pmsArray;
},
asset is an array from my add asset component
structure of asset
name: '',
detail: {
category: '',
manufacturer: '',
model: '',
serialNumber: '',
purchasePlace: '',
quantity: 1,
acquiredDate: '',
purchasePrice: '',
currentValue: '',
condition: '',
assetLocation: '',
retiredDate: '',
description: ''
},
files: {
fileList: []
}
hope this helps out some
the whole store file
import Vue from 'vue'
import Vuex from 'vuex'
import { states } from '../components/enums/enums'
import { getField, updateField } from 'vuex-map-fields'
import axios from 'axios'
Vue.use(Vuex);
const inventory = {
namespaced: true,
strict: true,
state: {
assets: {
items: []
},
categories: [],
manufacturers: [],
assetLocations: [],
conditions: ['New', 'Fair', 'Good', 'Poor']
},
getters: {
assetItems: state => state.assets.items,
getAssetById: (state) => (id) => {
return state.assets.items.find(i => i.id === id);
},
conditions: (state) => state.conditions,
categories: (state) => state.categories,
manufacturers: (state) => state.manufacturers,
assetLocations: (state) => state.assetLocations
},
mutations: {
createAsset (state, assets) {
state.assets.items.push(assets);
},
createCategories (state, category) {
state.categories.push(category);
},
createManufacturers (state, manufacturer) {
state.manufacturers.push(manufacturer);
},
createLocations (state, locations) {
state.assetLocations.push(locations);
}
},
actions: {
addToCategories ({ commit }, categories) {
commit('createCategories', categories);
},
addToManufacturers ({ commit }, manufacturers) {
commit('createManufacturers', manufacturers);
},
addToLocations ({ commit }, locations) {
commit('createLocations', locations);
},
populateAssets ({ dispatch }, asset) {
//return new Promise((resolve) => {
// assets.forEach((asset) => {
// commit('createAsset', asset);
// });
dispatch('postAsset', asset);
// resolve(true);
//});
},
addAsset ({ dispatch, /*getters*/ }, newAsset) {
//let assetCount = getters.assetItems.length;
//newAsset.id = assetCount === 0
// ? 1
// : assetCount++;
dispatch('populateAssets', [newAsset]);
},
async srcToFile(context, asset) {
const files = asset[0].files.fileList;
let pmsArray = [];
for (let f = 0; f < files.length; f++) {
var data = files[f].data;
let name = files[f].name;
let mimeType = files[f].type;
await fetch(data)
.then(function(res) {
const r = res.arrayBuffer();
console.warn('resource ', r);
return r;
})
.then(function(buf) {
console.warn('buffer: ', [buf]);
let file = new File([buf], name, { type: mimeType });
pmsArray.push(file);
});
}
console.warn(pmsArray);
return pmsArray;
},
async postAsset({ dispatch }, asset) {
const f = await dispatch('srcToFile', asset);
asset[0].files.fileList = f;
const fileData = asset[0].files.fileList;
const detailData = asset[0].detail;
const fData = new FormData();
fData.append('Name', asset[0].name);
Object.keys(detailData).forEach((key) => {
fData.append(`Detail.${key}`, detailData[key]);
});
for (var i = 0; i < fileData.length; i++) {
fData.append('Files', fileData[i]);
}
await axios({
method: 'post',
url: 'https://localhost:5001/api/Assets',
data: fData,
headers: { 'Content-Type': undefined }
})
.then(function(response) {
console.warn(response);
})
.catch(function(response) {
console.warn(response);
});
}
}
};
const maintenance = {
state: {
backup: []
},
strict: true,
getters: {},
mutations: {},
actions: {}
};
const assetProcessing = {
namespaced: true,
state: {
currentAsset: {
id: 0,
name: '',
detail: {
category: '',
manufacturer: '',
model: '',
serialNumber: '',
purchasePlace: '',
quantity: 1,
acquiredDate: '',
purchasePrice: '',
currentValue: '',
condition: '',
assetLocation: '',
retiredDate: '',
description: ''
},
files: {
fileList: []
}
},
filePosition: -1,
selectedItem: -1,
state: states.view,
isNewAsset: false
},
getters: {
getField,
getOpenAsset (state) {
return state.currentAsset
},
getSelectedAsset: (state, getters, rootState, rootGetters) => (id) => {
if (state.isNewAsset) return state.currentAsset
Object.assign(state.currentAsset, JSON.parse(JSON.stringify(rootGetters['inventory/getAssetById'](!id ? 0 : id))));
return state.currentAsset
},
appState: (state) => state.state,
getCurrentPosition (state) {
return state.filePosition
},
selectedAssetId: (state) => state.selectedItem
},
mutations: {
updateField,
setAsset (state, asset) {
Object.assign(state.currentAsset, asset)
},
setFiles (state, files) {
Object.assign(state.currentAsset.files, files)
},
newAsset (state) {
Object.assign(state.isNewAsset, true)
Object.assign(state.currentAsset, {
id: 0,
name: '',
detail: {
category: '',
manufacturer: '',
model: '',
serialNumber: '',
purchasePlace: '',
quantity: 1,
acquiredDate: '',
purchasePrice: '',
currentValue: '',
condition: '',
assetLocation: '',
retiredDate: '',
description: ''
},
files: {
fileList: []
}
})
},
updateSelectedItem (state, id) {
Vue.set(state, 'selectedItem', id);
},
updateState (state, newState) {
Vue.set(state, 'state', newState);
}
},
actions: {}
};
export const store = new Vuex.Store({
modules: {
inventory: inventory,
maintenance: maintenance,
assetProcessing
}
})
add asset is called when the user clicks the save button on the form
addAsset () {
this.$store.dispatch('inventory/addAsset', this.newAsset) <--- this calls add asset
this.$store.commit('assetProcessing/updateState', states.view);<-- this closes the window
},
So after much debugging we found that the eventbus was firing multiple times causing the excessive posting we added
beforeDestroy() {
eventBus.$off('passAssetToBeSaved');
eventBus.$off('updateAddActionBar');
},
to the AssetAdd.vue component and it eliminated the excessive posting of the asset.
I want to thank #phil for helping me out in this.

Vue - Vuetify server-side datatable bug

I noticed a bug with my vuetify server-side data table. When a data table contains no data and then I attempt to add a new one, it will be successful but it is not displayed in the table, I even checked my database. After I hit the refresh button of the browser, it now shows.
But when a data already exist (even just one), the newly added data automatically reflects in the table. I don't know what is causing this behavior and it only happens when there is no data. I think it has something to do with an empty table being rendered.
Template
<v-data-table
:headers="headers"
:items="tableData"
:editItem="this.editItem"
:deleteItem="this.deleteItem"
:options.sync="pagination"
:server-items-length="totalData"
:loading="loading"
dense
>
Script
export default {
data() {
return {
editedIndex: -1,
search: "",
loading: true,
pagination: {},
dialog: false,
valid: false,
validationErrors: '',
tableData: [],
totalData: 0,
departments: [],
tableItem: {
name: '',
departmend_id: '',
},
snackbar: {
enable: false,
name: '',
message: '',
},
headers: [
{ text: 'ID', value: 'id' },
{ text: 'Department Name', value: 'name' },
{ text: 'From Department', value: 'department' },
{ text: 'Created At', value: 'created_at' },
{ text: 'Action', value: 'action' },
],
rules: {
name: [
v => !!v || 'This field is required',
v => (v && v.length <= 50) || 'Field must be less than 50 characters'
]
}
}
},
watch: {
params: {
handler() {
this.getDataFromApi().then(data => {
this.tableData = data.items
this.totalData = data.total
})
},
deep: true
}
},
computed: {
params(nv) {
return {
...this.pagination,
query: this.search
}
},
formTitle() {
return this.editedIndex === -1 ? 'New Section' : this.tableItem.name
},
},
mounted() {
this.getDataFromApi().then(data => {
this.tableData = data.items
this.totalData = data.total
})
},
created() {
this.getDepartments()
},
methods: {
async getDataFromApi() {
this.loading = true
return new Promise((resolve, reject) => {
const { sortBy, sortDesc, page, itemsPerPage } = this.pagination
let search = this.search.trim().toLowerCase()
axios.get('/api/sections').then(res => {
let items = _.orderBy(res.data, ['created_at'], ['desc'])
const total = items.length
if (search) {
items = items.filter(item => {
return Object.values(item).join(",").toLowerCase().includes(search)
})
}
if (sortBy.length === 1 && sortDesc.length === 1) {
items = items.sort((a, b) => {
const sortA = a[sortBy[0]]
const sortB = b[sortBy[0]]
if (sortDesc[0]) {
if (sortA < sortB) return 1
if (sortA > sortB) return -1
return 0
} else {
if (sortA < sortB) return -1
if (sortA > sortB) return 1
return 0
}
})
}
if (itemsPerPage > 0) {
items = items.slice((page - 1) * itemsPerPage, page * itemsPerPage)
}
setTimeout(() => {
this.loading = false
resolve({
items,
total
})
}, 300)
})
})
},
async initialize() {
this.loading = true
let res = await axios.get('/api/sections')
this.tableData = _.orderBy(res.data, ['created_at'], ['desc'])
setTimeout(() => {
this.loading = false
}, 300)
},
async getDepartments() {
let res = await axios.get('/api/departments')
this.departments = _.orderBy(res.data, ['name'], ['asc'])
},
reset() {
this.$refs.form.reset()
},
close() {
this.dialog = false
this.$refs.form.reset()
setTimeout(() => {
this.editedIndex = -1
}, 300)
},
editItem(item) {
this.editedIndex = this.tableData.indexOf(item)
this.tableItem = Object.assign({}, item)
this.dialog = true
},
updateSnackbar(e) {
this.snackbar.enable = e
},
async deleteItem(item) {
let index = this.tableData.indexOf(item)
if(confirm('Are you sure you want to delete this item?') && this.tableData.splice(index, 1)) {
let res = await axios.delete('/api/sections/' + item.id)
this.snackbar.name = ''
this.snackbar.message = res.data.message
this.snackbar.enable = true
}
},
async save() {
if (this.editedIndex > -1) {
try {
Object.assign(this.tableData[this.editedIndex], this.tableItem)
let res = await axios.put('/api/sections/' + this.tableItem.id, this.tableItem)
this.snackbar.name = res.data.name
this.snackbar.message = res.data.message
} catch(error) {
if (error.response.status == 422){
this.validationErrors = error.response.data.errors
}
}
} else {
try {
let res = await axios.post('/api/sections', this.tableItem)
this.snackbar.name = res.data.name
this.snackbar.message = res.data.message
} catch(error) {
if (error.response.status == 422){
this.validationErrors = error.response.data.errors
}
}
}
await this.initialize()
this.snackbar.enable = true
this.close()
this.reset()
},
}
}
So after countless of trials, I have finally found the solution.
try {
let res = await axios.post('/api/departments', this.tableItem)
this.getDataFromApi().then(data => {
this.tableData = data.items
this.totalData = data.total
})
}

Get data in ag-grid

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)
},