Chris X
Chris X

Reputation: 23

Getting HTML from API in Vue.js

So, I have an API I need to retrieve data from. I'm using vue.js and axios. I have an app.vue file in which i import a component called Contests, in contests i'm making the api call, I'm able to retrieve the data whatsoever but it's HTML, and when I put it inside my component on the final screen it only shows HTML,anyone has any ideea? this is my code App component here

<template>
    <div>
        <app-contests> </app-contests>
    </div>
</template>

<script>
    import Contests from './components/Contests.vue';

    export default {
        components: {
            appContests: Contests
        }
    }
</script>

<style>

</style>

where i'm making the api call

<template>
    <div>
        <div class="container">
            {{info}} 
        </div>
        <div v-if="errored">
            <h1>We're sorry, we cannot retrieve this information at the moment. Please come back later.</h1>
        </div>
    </div>
</template>

<script>
    export default {
        data() {
            return {
                info: null
            }
        },
        mounted() {
            axios
              .get('myApiThatReturnsHtml')
              .then(response => {
                this.info = response;
              })
              .catch(error => {
                console.log(error);
                this.errored = true
              })
              .finally(() => this.loading = false)  
        }
    }

</script>

<style>

</style>

Upvotes: 2

Views: 6220

Answers (1)

Ashvin777
Ashvin777

Reputation: 1482

Since your response data is an HTML content, you need to use an appropriate handler to render that in DOM. Vue.js provide v-html attribute to add HTML in DOM.

<div class="container" v-html="info">
</div>

But be careful with it because it can lead to XSS attack - https://blog.sqreen.io/xss-in-vue-js/

Upvotes: 7

Related Questions