Passing data properties in vue js laravel component - javascript

Am new to Vue.js and I would like to pass the data propert value to my template.
I have:
export default {
name: "profile",
data: () => ({
user:[]
}),
mounted() {
axios
.get('/api/user')
.then(function (response) {
this.user = response
})
.catch(function (response) {
console.error(response);
});
}
}
In the HTML template I have:
<template>
<div>{{user.name }}</div>
</template>
Now I am getting an error of
cannot set property user of undefined
A console.log(response) produces:
name: "user 1", // name exists
email ...

Try using arrow function for axios callbacks
.then((response) => {
this.user = response
})
arrow function binds the components context as you expect.

In mounted:
mounted() {
var self = this;
axios.get('/api/user')
.then(function (response) {
self.user = response
})
.catch(function (response) {
console.error(response);
});
}
}

Related

How can I in Vue.js get axios response ( v-on:click ) (async / try,catch)?

Someone can help me, i'm trying to get object response from API whit axios in async function with try and catch.
I received: Promise { pending }.
How can i get my object?
in the template:
<div class="div-search-city">
<input v-model="inputCity" placeholder="insert city name"/>
<button id="buttonCity" #click="get()">Search city</button>
</div>
in the script:
<script>
import myFunction from './js/service.js';
export default {
name: 'Input',
data () {
return {
myData: {}
}
},
methods: {
get(){
this.myData = myFunction.axiosRequest(this.inputCity);
console.log(this.myData);
}
}
}
</script>
and this is my service.js file:
const axios = require('axios');
var myFunctions = {
async axiosRequest(city){
var options = {
method: 'GET',
url: 'https://api.waqi.info/feed/' + city + '/',
params: {
token: 'a1d2e0ee074e48f8bf....................'
}
};
try {
let response = await axios.request(options);
return response
}catch (error) {
console.error(error)
}
}
}
export default myFunctions
Thanks.
The way I do this is to return the promise from the service.js file and doing the await in the client. After the await resolves you can set the data to the bound variable in the Vue component.
<script>
import myFunction from './js/service.js';
export default {
name: 'Input',
data () {
return {
Data: {},
}
},
methods: {
async get(){
this.data = await myFunction.axiosRequest(this.inputCity);
console.log(this.data);
},
}
}
</script>

Send variable javascript to controller laravel to update vueJS

I´m traying send data from my modal to one controller for update data, but i don´t know how declare my variable and how i must send this variable...
my actual code is:
vuejs
<script>
export default {
data() {
return {
datosUsuario: [],
isOpen: false,
selectedItem: {},
nombreUsuario: nombreUsuario,
};
},
created: function () {
this.cargar();
},
methods: {
cargar: function () {
let url = "/getDatosPersonales";
axios
.get(url)
.then((response) => {
this.datosUsuario = response.data;
})
.catch((error) => console.error(error));
},
actualizar: function(){
let nombreUsuario = document.getElementById('nombre');
let url = "/actualizarDatos";
axios
.post(url)
.then((response) => {
console.log(response);
console.log(nombreUsuario);
})
.catch((error) => console.error(error))
},
setSelectedItem(item) {
this.selectedItem = item;
}
},
};
when i do click in my button this call a function "actualizar"
<input type="submit" class="btn btn-primary" value="Guardar" #click="actualizar">
i was check that if i do click in button go to my controller and it´s ok, but now i need to pass data in request for update, and i don´t know .
thanks so much for help
I get solve my problem, it´s very easy. share my solution
actualizar: function(){
let url = "/actualizarDatos";
axios
.post(url, {
idUsuario: this.datosUsuario.id,
nombreUsuario: this.datosUsuario.nombre,
email: this.datosUsuario.email,
direccion: this.datosUsuario.direccion,
})
.then((response) => {
console.log(response);
})
.catch((error) => console.error(error))
},

Axios - cannot change variable data value

I tried to change the variable data using axios, i am using vue-axios and vue cli 3.
This is the code:
const qs = require('qs')
export default {
name: 'Home',
data: function () {
return {
email: null,
errEmail: false,
baseUrl: 'https://www.example.com/isemail.php'
}
},
methods: {
next: function () {
},
err: function () {
this.axios.post(this.baseUrl + 'functions/isEmail.php', qs.stringify({
value: this.email
}))
.then(function (resp) {
this.errEmail = true
})
}
}
}
<div v-if="errEmail">Target Success</div>
Actually i am trying change the errEmail variable depend on the server callback like this:
this.errEmail = resp.data.isemail
but using constant seems not working too.
Change this
.then(function (resp) {
this.errEmail = true
})
to this
.then((resp) => {
this.errEmail = true
})
Or manually bind this
.then(function (resp) {
this.errEmail = true
}.bind(this))

Accessing variable from outsite of axios post

I'm trying to access a variable inside of axios call, but it returns an undefined error. Please see my code below.
new Vue({
el: '#app',
data(){
return {
roles: [{ display: 'disp' }]
}
},
methods: {
axios.post('{{ route('role.add') }}', {
})
.then((response, roles) => {
console.log(this.roles);
})
.catch(function(err){
console.log(err);
});
}
})
Error
Undefined
Solution [SOLVED]
Added global variable above the Vue.
Try to access without this. I don't see any purpose for using this.
const axios = require("axios");
var a = "some value";
axios.get('http://www.google.com').then(function () {
console.log(a);
}).catch(e => {
console.log(e, "ERROR");
})
Just remove this keyword and it will work:
var roles = [{ display: 'disp' }];
axios.post('{{ route('role.add') }}', {
})
.then(function(response){
console.log(roles);
})
.catch(function(err){
console.log(err);
});
Or use arrow function which is not preferred:
var roles = [{ display: 'disp' }];
axios.post('{{ route('role.add') }}', {
})
.then((response, roles) => {
console.log(this.roles);
})
.catch(function(err){
console.log(err);
});

Can I save Vue output as a Javascript array?

My Vue code below loads data from a database on page load. I know how to display it in a HTML file by using simple Vue methods. However, I want to save it as a Javascript array. The Javascript array will then be fed into a map (the map requires a Javascript array). Can I do so, and if so how?
var app = new Vue({
el: '#purchase',
mounted: function() {
this.allPurchases()
},
data: {
purchases: ""
},
methods: {
allPurchases: function(){
axios.get('http://localhost:3000/')
.then(function (response) {
console.log(response);
app.purchases = response.data;
})
.catch(function (error) {
console.log(error);
});
},
},
});
You should replace app.purchases by this.purchases :
var app = new Vue({
el: '#purchase',
mounted: function() {
this.allPurchases()
},
data() {
return{
purchases: []
}
},
methods: {
allPurchases: function(){
axios.get('http://localhost:3000/')
.then( (response) =>{
console.log(response);
this.purchases = response.data;
window.purchases = response.data;//to be used globally
})
.catch(function (error) {
console.log(error);
});
},
},
});
Simply change app.purchases = to this.purchases =

Categories