I'm learning Javascript by myself. I work with Vuejs & express on a CRUD App.
On a component, I request my back-end trough my api : localhost:3000/api/transport
Response give me all objects from the db.
With this response I want to implement an object to make a calendar using vue-val component.
This is my component script :
<script>
import VueCal from 'vue-cal'
import 'vue-cal/dist/vuecal.css'
import axios from 'axios'
export default {
components: { VueCal },
data() {
return {
transport: [],
events: [
/*{
start: '2021-01-21 10:30',
end: '2021-01-21 11:30',
title: 'Rdv dentiste',
content: '<i class="v-icon material-icons">local_hospital</i>',
class: 'health'
},*/
],
};
},
mounted() {
this.getTransport();
},
methods: {
getTransport: function() {
this.loading = true;
axios.get('http://127.0.0.1:3000/api/transport/')
.then((response) => {
this.transport = response.data;
this.implementEvents(this.transport);
this.loading = false;
})
.catch((err) => {
this.loading = false;
console.log(err);
})
},
implementEvents: function(transports) {
for(var transport in transports) {
console.log(transport.id)
this.events.push({
start: transport.startDate,
end: transport.endDate,
title: transporte.designation
})
}
}
}
};
</script>
implementEvents function take my response on parameter but I don't know why don't implement events array.
If I replace with code below, it's work.
implementEvents: function(transports) {
for(var transport in transports) {
console.log(transport.id)
this.events.push({
start: '2021-01-21 10:30',
end: '2021-01-21 10:30',
title: 'test'
Anyone have an idea ?
Try using forEach instead of for-in
implementEvents: function(transports) {
trnsports.forEach(transport => {
console.log(transport.id)
this.events.push({
start: transport.startDate,
end: transport.endDate,
title: transporte.designation
})
})
}
Related
First I defined Types, Severities, and Statuses as [] and returned them in data().
Then I filled them with data in the methods getTypes(), getSeverities(), and getStatuses().
I want to use Types, Severities, and Statuses in the method getName()(just has console.log() as an example for now).
I noticed when debugging getNames(), type in the second for loop is undefined. Is it because the method is using Type before it was assigned values in getTypes()? How can I make it work?
Note: Types, Severities, and Statuses do get assigned values in the methods getTypes(), getSeverities(), and getStatuses(), the issues is how to use the data in other methods.
<script>
import IssuesTable from '../MyIssuesPage/IssuesTable.vue'
import AddIssue from '../MyIssuesPage/AddIssue.vue'
import axios from 'axios'
export default {
props: ['id', 'project', 'issuesList', 'index'],
components: { IssuesTable, AddIssue },
data() {
return {
Issues: this.issuesList[this.index],
tab: null,
items: [{ tab: 'Issues' }, { tab: 'Calender' }, { tab: 'About' }],
Types: [],
Severities: [],
Statuses: [],
}
},
setup() {
return {
headers: [
{ text: 'Title', value: 'title' },
{ text: 'Description', value: 'description' },
{ text: 'Estimate', value: 'time_estimate' },
{ text: 'Assignees', value: 'userid' },
{ text: 'Type', value: 'issueTypeId' },
{ text: 'Status', value: 'issueStatusId' },
{ text: 'Severity', value: 'issueSeverityId' },
],
}
},
mounted() {
this.getTypes(), this.getSeverities(), this.getStatuses(), this.getNames()
},
methods: {
getTypes() {
axios
.get('http://fadiserver.herokuapp.com/api/v1/my-types')
.then(response => {
this.Types = response.data
})
.catch(error => {
console.log(error)
})
},
getSeverities() {
axios
.get('http://fadiserver.herokuapp.com/api/v1/my-severities')
.then(response => {
this.Severities = response.data
})
.catch(error => {
console.log(error)
})
},
getStatuses() {
axios
.get('http://fadiserver.herokuapp.com/api/v1/my-status')
.then(response => {
this.Statuses = response.data
})
.catch(error => {
console.log(error)
})
},
getNames() {
for (var issue of this.Issues) {
for (var type of this.Types) {
if (issue.issueTypeId == type.id) console.log('test')
}
}
},
},
}
</script>
First of all, use created() instead of mounted() for calling methods that fetch data.
Next, you need to call getNames() only after all fetch methods complete.
created() {
this.getTypes()
.then(this.getSeverities())
.then(this.getStatuses())
.then(this.getNames());
}
In order to chain methods like this you need to put return statement before each axios like this
getTypes() {
return axios
.get("https://fadiserver.herokuapp.com/api/v1/my-types")
.then((response) => {
this.Types = response.data;
})
.catch((error) => {
console.log(error);
});
}
In this component, I see you are receiving issuesList and index props from the outside. I cannot know those values but you can console.log both of them inside created() and see what is happening because issuesList[index] is undefined.
That probably means issuesList is an array and that index does not exist in that array.
I'm trying to pass data from vue component to blade file. I try to create props but it's didn't work for me. Is it any possible to pass the object to props to get the data? I'm new laravel. I want to pass data which subject, message, days, condition and module name to blade file(view).
I kept searching for this but couldn't find an answer that will make this clear.
Thanks!
blade.php
<div id="app">
<email-component
email_edit_route="{{ route('havence.automail.edit',['id'=>$mailTemplates->id]) }}"
>
</email-component>
</div>
Vue.js
<script>
import Vue from 'vue'
import axios from 'axios'
import MarkdownIt from 'markdown-it'
import ClassicEditor from '#ckeditor/ckeditor5-build-classic';
var msg_editor;
const md = new MarkdownIt({
linkify: true
})
export default {
props: ['email_creation_link', 'email_index_route', 'email_edit_route','conditions','modules'],
components: {
},
data() {
return {
template: {
subject: '',
message: '' ,
days: '',
condition_id: 1,
},
options:[
{
display:'Client Name',
actual:'Client name'
},
{
display:'Joined Date',
actual:'Joined date'
},
{
display:'Module Name',
actual:'Module name'
},
{
display:'Last Seen',
actual:'Last seen'
},
],
showName: false,
}
},
mounted(){
var self = this;
ClassicEditor
.create(document.querySelector( "#msg"),
{
})
.then(editor => {
msg_editor = editor;
editor.model.document.on( 'change:data', () => {
self.template.message = msg_editor.getData();
});
})
.catch(error => {
console.error(error);
})
},
methods: {
//Drag items
dragstart: function(item, e){
this.draggingItem = item;
e.dataTransfer.setData('text/plain', item.actual);
},
dragend: function(item,e) {
e.target.style.opacity = 1;
},
dragenter: function(item, e) {
this.draggingItem = item;
},
//content
replaceVariables(input)
{
let updated = input
return updated
},
//hidecontent
showHide: function(e)
{
console.log("Show "+e.target.value+ " fields")
this.showName = e.target.value !== ''
},
fetch()
{
//request data
axios.get(this.email_index_route,this.template)
.then((res) => {
this.template = res.data.template;
})
},
save()
{
//save data to db
axios.post(this.email_index_route, this.templates)
.then((res) => {
alert('Mail sent successfull!')
})
},
addToMail: function(type, text)
{
if (type == 'message') {
this.template.message += text;
msg_editor.setData(this.template.message);
}
},
//user name replace
replaceVariables() {
return this.replaceVariables(this.options || '')
},
}
}
</script>
Quick solution. : why not store data in local storage and fetch it from laravel blade ?
Next solution: you can fire global event from vue and listen on laravel blade .
why dont you send the data through ajax post call and get the data from the controller ?
then pass the data object to blade template.
I'm using vue in laravel and trying to get a controller function that I'm hitting to return the data so that I can use it in the data() section of my vue template.
I know the controller function returns what I need, but I'm not so sure how I need to handle the return/response in the axios call in order to start placing the data into the data() function in vue
Blade/Vue template
import moment from 'moment'
export default {
name: 'calendar',
data () {
return {
events: [
{
title: 'test',
allDay: true,
start: '2019-08-17',
},
],
config: {
defaultView: 'month',
eventRender: function(event, element) {
console.log(event)
}
},
}
},
created() {
this.fetchTasks();
},
methods: {
fetchTasks() {
axios.get('/landing/tasks' )
.then((response) => {
// handle success
this.assetOptions = response.data;
})
.catch(function (error) {
// handle error
console.log(error);
})
.finally(function () {
});
}
}
}
Route
Route::get('/landing/tasks', 'landingController#getTasks')
->name('landing/tasks');
Controller
public function getTasks()
{
$getTask = Task::getTaskForLanding();
$result = array();
foreach($getTask as $id => $task){
$result[$task->taskt_id][] = $task;
}
}
If you are certain that the Controller returns what you need, the only thing you are missing is declaration of assetOptions. To be able to assign response.data to assetOptions later on, you have to declare it in the data function first.
data() {
return {
...
assetOptions = []; // assuming you are expecting an array
...
};
}
Once that is done, you are all set.
Good afternoon everyone I'm having a problem converting json to csv, I'm using a lib I found at https://github.com/angeliquekom/vue-json-to-csv, to be very interesting, but I'm having trouble passing an arrau for component.
my code:
<template>
<vue-json-to-csv :json-data="data"
:labels="{
id: { title: 'id' },
co_tipo_nota: { title: 'co_tipo_nota' },
ds_nota: { title: 'ds_nota' },
ds_outro_criterio: { title: 'ds_outro_criterio' },
ds_nofl_avaliacao_anonimata: { title: 'fl_avaliacao_anonima' },
dt_nota: { title: 'dt_nota' },
}"
#success="val => handleSuccess(val)"
#error="val => handleError(val)">
<button>
<b>My custom button</b>
</button>
</vue-json-to-csv>
</template>
<script>
import VueJsonToCsv from 'vue-json-to-csv'
import { baseApiUrl } from '#/global'
import axios from 'axios'
export default {
name: 'DowloadCvsThree',
components: {
VueJsonToCsv,
},
data: function() {
return {
mode: 'save',
nota: {},
notas: [],
}
},
props: {
notas: Array
},
methods: {
loadUsers() {
const url = `${baseApiUrl}/notas`
axios.get(url).then(res => {
this.notas = res.data
})
},
mounted() {
this.loadUsers()
}
}
}
</script>
<style>
</style>
the error return is ?
[o erro][1]
[1]: https://i.stack.imgur.com/llHeZ.png
can anybody help me? I'm trying to pass an array to the json-to-csv: json-data = "data" component, but the date is not an array with I do?
he address of lib npm is: https://github.com/angeliquekom/vue-json-to-csv
awaiting return?
I'm need this array as a parameter but when I try to use it, I only receive a observer. How to use the information of the array instead of the observer?
When I console.log in the function that retrieves the information from the DB it shows the data as it should.
I don't know what else to do, I've already tried other ways to try to solve this but I wasn't sucessfull.
<script>
import { ClientTable } from 'vue-tables-2';
import Vue from 'vue';
import Multiselect from 'vue-multiselect';
import options from './../../../commons/helpers/grid.config';
import edit from './edit';
Vue.use(ClientTable, options, false, 'bootstrap4', 'default');
Vue.component('multiselect', Multiselect);
export default {
name: 'Reporting',
removable: false,
components: {
edit,
},
showLoading: true,
data() {
return {
selected: null,
columns: ['period', 'costCenter', 'hours', 'actions'],
reportingsList: [],
periods: [],
totalHours: 0,
options: {
sortable: [],
columnsClasses: {
actions: 'action-column text-center',
period: 'period-column',
costCenter: 'costCenter-Column',
hours: 'hours-column',
},
},
};
},
mounted() {
this.getAll();
},
methods: {
getTotalHours(reportings) {
let result = 0;
for (let i = 0, length = reportings.length; i < length; i += 1) {
result += reportings[i].hours;
}
console.log(result); //eslint-disable-line
console.log(this.reportingsList); //eslint-disable-line
this.totalHours = result;
},
getAll() {
const url = 'reportings/getAll';
this.$http().get(url).then((response) => {
this.reportingsList = response.data;
console.log(this.reportingsList.length);//eslint-disable-line
});
this.getTotalHours(this.reportingsList);
}
</script>
It's asynchronous code, this.getTotalHours will be execute before this.$http.get finish.
You need to chain .then
this.$http().get(url).then((response) => {
this.reportingsList = response.data;
console.log(this.reportingsList.length);//eslint-disable-line
return response.data
}).then(() => {
this.getTotalHours(this.reportingsList);
});