I have the following code and would like to know how I can implement a try / catch with async / await executing the same function:
import Vue from 'vue'
import axios from 'axios'
new Vue({
el: '#app',
data: {
skills: [],
},
mounted() {
axios
.get('http://localhost:8080/wp-json/api/v1/skills')
.then(response => {
this.skills = response
}).catch(err => (console.log(err)))
}
})
Thank you!
see code below:
var app = new Vue({
el: '#app',
async mounted() {
try{
let response = await axios.get('http://localhost:8080/wp-json/api/v1/skills')
this.skills = response
}catch(err){
console.log(err)
}
}
})
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<div id="app">
</div>
Related
I have a GET request with axios and get a .png file back and want to show this inside my template. I can't use a path url, because the image is each time differently.
This is my fastapi route.
from io import BytesIO
from fastapi.responses import Response
#app.get("/image", response_class=Response)
def load_image():
...
buffer = BytesIO()
img.save(buffer, format="PNG")
return Response(content=buffer.getvalue(), media_type="image/png")
This is the vue component:
<script>
export default {
name: "Example",
data() {
return {
image: null;
};
},
methods: {
async loadImage() {
const url = "/image";
const response = await $axios.get(url, { responseType: "arraybuffer" });
if (response.status == 200) {
const base64string = btoa(String.fromCharCode(...new Uint8Array(response.data)));
console.log(base64string); // -> this is a empty string
this.image = 'data:image/png;base64,' + base64string;
}
},
mounted() {
this.loadImage();
},
};
</script>
<template>
<div>
<img :src="image" title="Image" />
</div>
</template>
You can...
get the data as a blob by passing { responseType: "blob" } to axios
convert the blob to base64 with FileReader (used blobToData function from https://stackoverflow.com/a/63372663/197546)
use the base64 data as the image src
example:
const app = Vue.createApp({
data() {
return {
imageSrc: null,
};
},
methods: {
async loadImage() {
const url =
"https://images.unsplash.com/photo-1664300067908-84e8beb52a8f?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHwyNXx8fGVufDB8fHx8&auto=format&fit=crop&w=500&q=60";
const response = await axios.get(url, { responseType: "blob" });
if (response.status == 200) {
const base64data = await blobToData(response.data);
this.imageSrc = base64data;
}
},
},
mounted() {
this.loadImage();
},
});
app.mount("app");
function blobToData(blob) {
return new Promise((resolve) => {
const reader = new FileReader()
reader.onloadend = () => resolve(reader.result)
reader.readAsDataURL(blob)
})
}
<script src="https://unpkg.com/vue#next/dist/vue.global.prod.js"></script>
<script src="https://unpkg.com/axios#0.27.2/dist/axios.min.js"></script>
<app>
<img :src="imageSrc" v-if="imageSrc"/>
</app>
As Chris pointed out, you can also...
get the data as an array buffer by passing { responseType: "arraybuffer" } to axios
convert array to base64 data using btoa(String.fromCharCode(...new Uint8Array(response.data)))
build the src data by adding prepending the content type to the base64 data
example:
const app = Vue.createApp({
data() {
return {
imageSrc: null,
};
},
methods: {
async loadImage() {
const url =
"https://images.unsplash.com/photo-1664300067908-84e8beb52a8f?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHwyNXx8fGVufDB8fHx8&auto=format&fit=crop&w=500&q=60";
const response = await axios.get(url, { responseType: "arraybuffer" });
if (response.status == 200) {
const b64 = btoa(String.fromCharCode(...new Uint8Array(response.data)));
const imgData = "data:" + response.headers['content-type'] + ";base64," + b64;
this.imageSrc = imgData;
}
},
},
mounted() {
this.loadImage();
},
});
app.mount("app");
<script src="https://unpkg.com/vue#next/dist/vue.global.prod.js"></script>
<script src="https://unpkg.com/axios#0.27.2/dist/axios.min.js"></script>
<app>
<img :src="imageSrc" v-if="imageSrc"/>
</app>
I have something like this in a Laravel API for one of the routes:
return response()->json(['message' => "Couldn't Price the car"], 500);
In the front-end, I have
try {
let data = await Axios.get("blax", {});
} catch(err) {
console.log(err.message);
}
err.message just shows default message:
request failed with status code 500
instead of showing:
Couldn't Price the car
How do I show my custom message?
try using err.response.message
try{
let data = await Axios.get("blax", {});
}catch(err){
console.log(err.response.message);
}
It seems to me that it catches perfectly:
new Vue({
el: "#demo",
data: {
response: null,
},
async created() {
try {
let data = await axios.get("https://httpstat.us/500", {});
} catch (err) {
console.log('ss', err.message);
this.response = err.message;
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.0/axios.min.js"></script>
<div id="demo">
Error: {{response}}
</div>
If you want to minimize your code, you can do .catch directly on the axios call, like so:
let data = axios.get("https://httpstat.us/500", {}).catch(e => e.message);
This catch also uses arrow function stripped down to the minimal. Here is an example of the same arrow function, just "normal":
let data = axios.get("https://httpstat.us/500", {}).catch((e) => {return e.message});
new Vue({
el: "#demo",
data: {
response: null,
},
async created() {
this.response = await axios.get("https://httpstat.us/500", {}).catch(e => e.message);
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.0/axios.min.js"></script>
<div id="demo">
Error: {{response}}
</div>
Updated
responseJSON is not defined it's just response
try this the console.log(err.response.message) as following:
try{
let data = await Axios.get("blax", {});
}catch(err){
console.log(err.response.message);
}
I have a class with a variable in the constructor, I try to make a ajax request and update a variable. But the variable is not in my scope. what can I do?
import Axios from "axios";
class ajaxTest{
constructor() {
this.resultOfAjax=" Mein Test";
}
set(id){
return new Promise(function(resolve, reject) {
Axios.get('/api/v1/ajax/'+id)
.then(function (response) {
this.resultOfAjax=response.data;
resolve(200);
console.log("Test");
});
})
}
}
export default ajaxTest;
Also I try to update my loadingCircle variable, but it is not working. I think it is the same mistake. Is this right?
const app = new Vue({
el: '#app',
data: {
loadingCircle: true,
ajaxTest: new ajaxTest()
},
methods: {
handleClick: function(id) {
console.log("Das ist ein Test die ID ist:"+id);
this.ajaxTest.set(id).then( function(status){
console.log("Status "+status);
this.loadingCircle=false;
});
}
},
components: {
examplecomponent
}
});
If you use a function, then the this inside it is not the same as the this outside. The solution is to use the fat arrow notation instead.
const app = new Vue({
el: '#app',
data: {
loadingCircle: true,
ajaxTest: new ajaxTest()
},
methods: {
handleClick: (id) => {
console.log("Das ist ein Test die ID ist:"+id);
this.ajaxTest.set(id).then( (status) => {
console.log("Status "+status);
this.loadingCircle=false;
});
}
},
components: {
examplecomponent
}
});
I have a non-SPA web app that has Vue components and that works very well. However, I am looking for a way to load HTML that contains Vue via an external API.
So, I simply make a call to /ajax/dialogbox/client/add which is returning HTML containing Vue components, like:
<h1>Add client</h1>
<div>My static content</div>
<my-component></my-component>
but obviously <my-component></my-component> does not do anything.
In Angular 1 I was using $compile service to compile the HTML before output.
Is there a way to do the same in Vue?
There is a compile function available in Vue that compiles templates to render functions. Using the compiled functions requires a little more detail than you have provided (if you needed to use the returned template with data, for example), but here is one example.
console.clear()
Vue.component("my-component",{
template: `<h1>My Component</h1>`
})
const template = `
<div>
<h1>Add client</h1>
<div>My static content</div>
<my-component></my-component>
</div>
`
new Vue({
el: "#app",
data:{
compiled: null
},
mounted(){
setTimeout(() => {
this.compiled = Vue.compile(template)
}, 500)
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.js"></script>
<div id="app">
<component :is="compiled"></component>
</div>
Note that in the example, I wrapped your example template in a div tag. Vue requires that there is on a single root element for a Vue or component.
After many hours, I managed to pass some properties to the component to be compiled.
In the HTML body:
<!-- some where in the HTML body -->
<div id="vCard2">
<component :is="compiled"></component>
</div>
<script>
var vmCard2 = new Vue({
el: '#vCard2',
data: {
compiled: null,
status: ''
},
methods: {
show: function () {
// macro is some dynamic string content or html template that contains mustache
var macro = this.status == 'some_switch' ? '...{{payment.status}}...' : '...{{refund.status}}...';
Vue.component('cp-macro', {
data: function () {
return {
payment: vmCard1.payment,
refund: vmCard1.refund
}
},
template: '<span>'+macro+'</span>'
})
this.compiled = Vue.compile('<cp-macro></cp-macro>');
},
hide: function () {
this.compiled = null; // must remove for the next macro to show
}
}
})
</script>
I use this method in my project for rendering templates as reactive component. All I need is passing in props URL for download template or template for immediate render:
<div id="app"></div>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script src="https://unpkg.com/vue#3/dist/vue.global.js"></script>
<script>
const { createApp, defineComponent, markRaw } = Vue;
createApp({
template: `
<component v-if="component" :is="component"/>
<span v-else>Component is loading...</span>
`,
data: () => {
return {
component: undefined
}
},
provide: {
message: 'Hello Vue!'
},
mounted() {
setTimeout(async () => {
this.component = await this.defineRawComponent('<span>{{ message }}</span>')
}, 1000);
},
methods: {
async defineRawComponent(template, url) {
if (!template && !url) {
throw new Error('URL and template is not defined');
}
try {
let html = template;
if (!html) {
const { data } = await axios.get(url);
html = data;
}
return Promise.resolve(
markRaw(
defineComponent({
name: 'RawContent',
template: html,
inject: ['message']
})
)
);
} catch (err) {
return Promise.reject(err);
}
}
}
}).mount('#app')
</script>
(using laravel 5.4 and vue.js 2x)
I use router.beforeEach() to handle authorization in my app.
But, my function router.beforeEach() is only loading on the moment after login. If I refresh the page the function isn't called again.
Here is my code:
import router from './routes.js';
require('./bootstrap');
const app = new Vue({
el: '#app',
router,
});
router.beforeEach((to,from,next) => {
if(to.meta.requiresAuth){
authUser = '';
const authUser = JSON.parse(window.localStorage.getItem('authUser'))
if(authUser && authUser.access_token){
next()
}else{
next({
path: '/login',
query: { redirect: to.fullPath }
})
}
}
next()
})
The full project: https://github.com/jrpikong/wingding
The way to check if the current route requires authentication is documented here: https://router.vuejs.org/en/advanced/meta.html
Change your beforeEach method to this:
router.beforeEach((to,from,next) => {
if(to.matched.some(record => record.meta.requiresAuth)){
// do something
}
next();
}
As mentioned in the Documentation,
All route records matched by a route are exposed on the $route
object (and also route objects in navigation guards) as the
$route.matched Array. Therefore, we will need to iterate over
$route.matched to check for meta fields in route records.
router.beforeEach((to,from,next) => {
if(to.matched.some(record => record.meta.requiresAuth)){
authUser = '';
const authUser = JSON.parse(window.localStorage.getItem('authUser'))
if(authUser && authUser.access_token){
next()
}else{
next({
path: '/login',
query: { redirect: to.fullPath }
})
}
}
next()
})
I just switched the position of router.beforeEach to be before
const app = new Vue({
el: '#app',
router,
});
So, in full, the code looks like this:
import router from './routes.js';
require('./bootstrap');
router.beforeEach((to,from,next) => {
if(to.matched.some(record => record.meta.requiresAuth)){
const authUser = JSON.parse(window.localStorage.getItem('authUser'))
if(authUser && authUser.access_token){
next()
}else{
next({
path: '/login',
query: { redirect: to.fullPath }
})
}
}
next()
})
const app = new Vue({
el: '#app',
router,
});