How to extract axios response data into variables? - laravel

In routes, I define a route "/ajax/tutorials/unique/images" that returns the below output:
{
"data": [
{
"path": "/images/posts/1474360249_qDhAVF0mA4TnCVUmfcIpkNtvEkyhpV.png"
},
{
"path": "/images/posts/1475575942_ZjuBj3u1rIvxdz1sK0pAuufzY8yjCT.png"
},
{
"path": "/images/posts/1476871481_H63O2o55sBg8Qx1bf6S8wW1M82XXJ1.png"
},
{
"path": "/images/posts/1476896115_JdyLpsxpcfL8kcpUwpFURV963WdeNa.png"
},
{
"path": "/images/posts/1487368925_RSouQqnDiu1ieBGfWStfHlodcptVWA.png"
},
{
"path": "/images/posts/1487368919_iAJUQpd3qx7RTB3ZnMsND0KmjrKrKu.png"
}
],
"paginator": {
"total_count": 15,
"total_pages": 3,
"current_page": 1,
"limit": 6
}
}
I wrote this code in app.js file:
new Vue({
el: '#app',
data: {
images: [],
pagination: [],
},
mounted() {
axios.get('/ajax/tutorials/unique/images')
.then(function (response) {
this.images = response.data.data;
this.pagination = response.data.paginator;
console.log(response.data.data);
console.log(response.data.paginator);
});
}
});
The images and pagination array that I define in app.js don't have any value after running this code, but in the browser console I can see the output:
But Vue doesn't set the response to variables:
When I use arrow function for callback it works, the problem is that I want to set two variable.
new Vue({
el: '#app',
data: {
images: [],
pagination: [],
},
mounted() {
axios.get('/ajax/tutorials/unique/images')
.then(response => this.images = response.data.data);
}
});

Oh I didn't know that, We can use array in arrow function for callback, So I changed code like below, and it's work
axios.get('/ajax/tutorials/unique/images')
.then( response => [
this.images = response.data.data,
this.pagination = response.data.paginator,
]);

You need to return a function from data.
data: function(){
return {
images: [],
pagination: [],
}
}
This is how Vue will observe the images and pagination changes later when you component runs.

You could simply do this:
axios.get('/ajax/tutorials/unique/images')
.then(response => {
this.images = response.data.data
this.pagination = response.data.paginator
console.log(response.data.data)
console.log(response.data.paginator)
})

Related

facing problem in vue apexchart dynamic data set from api

I am try to create vue barchart & using apexChartData.
Here is my code
export default{
components: {
VueApexCharts
},
data () {
return {
barChart: {
series: [{
data: []
}],
chartOptions: {
plotOptions: {
bar: {
horizontal: true
}
},
dataLabels: {
enabled: false
},
xaxis: {
categories: []
}
}
}
},
methods: {
myFunction() {
this.$vs.loading();
axios.get("/api/auth/nameofapi").then(response => {
this.barChart.series[0].data = response.data[0]['data'];
this.barChart.chartOptions.xaxis.categories = response.data[1]['categories'];
this.$vs.loading.close();
}).catch(error => {
this.$vs.loading.close()
this.errorResponse(error);
});
}
},
mounted () {
this.myFunction();
}
}
My API Response payload like
[{"data":[4,1]},{"categories":["xyz","abc"]}]
After doing this bar chart is not loading, i am not sure where i am doing mistake, sorry for repeating this post if already exist but i just post what i am facing.
Any Help
Thanks in advance

Add action buttons in vue.js frontend when using server side dataTables

How to add action buttons in frontend vue.js when using server side dataTables?
here is what i have so far, this code is working, but action buttons not give the request when clicking. (the alert is not also firing). the action buttons are showing and calling to editTaxGroup()
$(document).ready(function() {
let tax = 1;
self.dataTable = $("#tax_groups2").DataTable({
serverSide: true,
ajax: {
"columns": [
{ "data": "tax_group_name" },
{ "data": "country.country_name" },
{ "data": "tax_rate_percentage" },
{ "data": "Edit" },
{ "data": "Delete" }
],
data: {
"token": localStorage.getItem("token"),
},
url: 'api/v1/get-tax-groups',
dataFilter: function(data){
var json = jQuery.parseJSON( data );
json.recordsTotal = 100;
json.recordsFiltered = 100;
self.tax_groups = data.data;
return JSON.stringify( json ); // return JSON string
}
},
columns: [
{data: "tax_group_name"},
{data: "country.country_name",},
{data: "tax_rate_percentage"},
{data: "Edit"},
{data: "Delete"},
],
"columnDefs": [
{
"targets": [ -2 ],
"data":"id",
"defaultContent" : '<i class="fas fa-pen"></i>'
},
{
"targets": [ -1 ],
"data":"id",
"defaultContent" : '</i>'
}
],
});
})
$('#tax_groups2 tbody ').on('click', '#edit', function () {
for (let key in self.tax_groups){
alert(1)
console.log(key);
if(self.tax_groups.hasOwnProperty(key)){
console.log(`${self.tax_groups[key]}`)
}
}
} );
});
},
This isn't using Vue at all. You could actually more efficiently use Vue to generate these tables dynamically and set buttons as well. You may want to remove the Vue tag or re-ask the question.

How to watch and set dynamically a variable?

Hi it's my first post on StackOverflow.
I'm working on for translating dynamically a website. I'm using the package vuejs-localization.
How can I switch language directly?
I'm working with the latest version of VueJS and Laravel.
This is my code on my language selector:
export default {
name: "LanguageDropDown",
data() {
return {
languages: [
{
lang: "fr",
text: "Français",
icon: "fr",
},
{
lang: "gb",
text: "English",
icon: "gb",
},
{
lang: "us",
text: "US",
icon: "us"
},
],
};
},
computed: {
getCurrentLang: function() {
return this.$lang.getLang();
},
},
methods: {
setLanguage(lang) {
this.$root.$emit("setLang", lang);
},
setLang(lang, index) {
this.$root.$emit("setLang", this.languages[index].languages[lang], index);
},
},
};
And this is what is in my App.js :
const app = new Vue({
el: '#app',
router,
data() {
return {
lang: 'fr'
};
},
created() {
this.$lang.setLang( this.lang );
},
mounted() {
let _this = this;
this.$root.$on( 'setLang', function( lang ){
_this.lang = lang ;
console.log(_this.lang);
});
},
watch: {
lang :{
handler(val){
this.lang = val;
console.log('changed to :' + this.lang);
},
},
},
})
I expect a translation by changing the variable 'fr' to 'us' or 'gb' but the log says that the lang is switching but nothing happened ...
Thanks for your help.
To make language changes, you need to call this.$lang.setLang. You can do it in watch
watch: {
lang :{
handler(val){
this.lang = val;
this.$lang.setLang(val)
console.log('changed to :' + this.lang);
},
},
},

Vue: event emitted is not getting picked up

I am able to pick up fire emitgetcartitems but for some reason the other listener, emitaddnotes, is not firing handleAddNotes(). I checked in context of the component as well by checking this.$listeners and I only saw emitgetcartitems listed for it. I'm not sure why the other event is not working at all.
blade template
<div id = "app">
<Modal
:modal-type="modalType"
:selected-product="selectedProduct"
:variant-data="variantData"
#emitgetcartitems="handleGetCartItems"
#emitaddnotes="handleAddNotes"
>
</Modal>
<Cart>
</Cart>
</div>
app.js
window.Vue = require('vue');
window.axios = require('axios');
Vue.component('Modal',
require('./components/Modal.vue').default);
new Vue({
el: "#app",
data() {
return {
modalType: null,
orderNotes: null,
couponCode: null,
selectedProduct: {},
variantData: [],
cart: {}
}
},
methods: {
handleChangeTab: function(tab) {
this.activeTab = tab
},
handleHideFlashMsg: function() {
this.flashStatus = false
},
handleAddNotes: function(){
console.log("!!!!!!!")
},
handleGetCartItems: function() {
axios
.get('/api/a-cart')
.then(response => {
this.cart = response.cart;
});
},
}
)}
Modal.vue
<template>
<div>
<button v-on:click="addNotes()"></button>
</div>
</template>
<script>
export default {
data() {
return {
couponInput: '',
}
},
props: {
selectedProduct: {type: Object},
orderNotes: {type: String},
couponCode: {type: String}
},
methods: {
getCartItems: function() {
console.log("GET CART")
this.$emit('emitgetcartitems')
},
addNotes: function() {
console.log("ADD NOTES")
this.$emit('emitaddnotes')
},
}
}
</script>

I want to show the value of label inside the pie graph. (vue-chartjs / pieceLabel)

I am a student studying vue.
I used Vue-chartjs to draw a graph, and I'd like to display the value on a pie graph.
But I don't know what to do.
Please help me...
the current situation (image) : enter image description here
My wish (image) : enter image description here
Vue.component('pie-chart', {
extends : VueChartJs.Pie,
props: ['data', 'options'],
mounted(){
this.renderPieChart();
},
computed: {
attendanceData : function(){
return this.data
}
},
methods : {
renderPieChart : function(){
this.renderChart(
{
labels: ['a','b','c','d'],
datasets: [{
backgroundColor: ['#10a236', '#f9cd41', '#fe7272', '#5c7add'],
data: [10,20,30,40]
}]
},
{
responsive: true,
maintainAspectRatio: false,
pieceLabel: {
render: 'value',
precision: 1,
}
}
)
}
},
watch : {
attendanceData : function(){
this.$data._chart.destroy();
this.renderPieChart();
}
}
});
As The dicusstion on tooltip of chart.js at Stackoverflow, uses plugin is one solution.
then as Vue chart.js guide said,
in mounted(), uses this.addPlugin to add your plugin like below demo:
Vue.config.productionTip = false
//below plugin is copied from https://stackoverflow.com/a/37989832/5665870
let pluginConfig = {
id: 'my-plugin',
beforeRender: function (chart) {
if (chart.config.options.showAllTooltips) {
// create an array of tooltips
// we can't use the chart tooltip because there is only one tooltip per chart
chart.pluginTooltips = [];
chart.config.data.datasets.forEach(function (dataset, i) {
chart.getDatasetMeta(i).data.forEach(function (sector, j) {
chart.pluginTooltips.push(new Chart.Tooltip({
_chart: chart.chart,
_chartInstance: chart,
_data: chart.data,
_options: chart.options.tooltips,
_active: [sector]
}, chart));
});
});
// turn off normal tooltips
chart.options.tooltips.enabled = false;
}
},
afterDraw: function (chart, easing) {
if (chart.config.options.showAllTooltips) {
// we don't want the permanent tooltips to animate, so don't do anything till the animation runs atleast once
if (!chart.allTooltipsOnce) {
if (easing !== 1)
return;
chart.allTooltipsOnce = true;
}
// turn on tooltips
chart.options.tooltips.enabled = true;
Chart.helpers.each(chart.pluginTooltips, function (tooltip) {
tooltip.initialize();
tooltip.update();
// we don't actually need this since we are not animating tooltips
tooltip.pivot();
tooltip.transition(easing).draw();
});
chart.options.tooltips.enabled = false;
}
}
}
Vue.component('pie-chart', {
extends : VueChartJs.Pie,
props: ['data', 'options'],
mounted(){
this.addPlugin(pluginConfig);
this.renderPieChart();
},
computed: {
attendanceData : function(){
return this.data
}
},
methods : {
renderPieChart : function(){
this.renderChart(
{
labels: ['a','b','c','d'],
datasets: [{
backgroundColor: ['#10a236', '#f9cd41', '#fe7272', '#5c7add'],
data: [10,20,30,40]
}]
},
{
responsive: true,
maintainAspectRatio: false,
pieceLabel: {
render: 'value',
precision: 1
},
showAllTooltips: true
}
)
}
},
watch : {
attendanceData : function(){
//this.$data._chart.destroy();
//this.renderPieChart();
}
}
})
var vm = new Vue({
el: '#app',
data: {
message: 'Hello World'
}
})
<script src="https://unpkg.com/vue#2.5.16/dist/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.min.js"></script>
<script src="https://unpkg.com/vue-chartjs/dist/vue-chartjs.min.js"></script>
<div id="app">
<pie-chart></pie-chart>
</div>

Resources