Home > OS >  how to render the html dynamically in vue
how to render the html dynamically in vue

Time:12-30

a vue code below will load a html dynamically and I want to render this part of html into GUI. how would I do this?

<template>

</template>

<script>
import request from '@/utils/request';
export default {
        name: 'Personalinforadm',
        data() {
            return {
              html:''
            }
        },
        created() {
            this.loadHtml();
        },
        methods: {
            loadHtml(){
                request({ url: '/page/html', method: 'get'})
                .then(resp => {
                    this.html = resp.data;
                    this.renderHtml();
                }).catch(error => {
                    console.log(error);
                }); 
            },
            renderHtml(){
               // how to render the html into the UI
            }
        }
}

CodePudding user response:

<template>
  <div v-html='html' />
</template>
<script>
import request from '@/utils/request';
export default {
        name: 'Personalinforadm',
        data() {
            return {
              html:''
            }
        },
        created() {
            this.loadHtml();
        },
        methods: {
            loadHtml(){
                request({ url: '/page/html', method: 'get'})
                .then(resp => {
                    this.html = resp.data;
                }).catch(error => {
                    console.log(error);
                }); 
            },
           
        }
}
</script>

CodePudding user response:

You can achieve this by using v-html as follows:

<template>
  <div v-html="html"></div>
</template>

<script>
  import request from '@/utils/request';
  export default {
    name: 'Personalinforadm',
    data() {
      return {
        html:''
      }
    },
    created() {
      this.loadHtml();
    },
    methods: {
      loadHtml() {
        request({ url: '/page/html', method: 'get'})
          .then(resp => {
            this.html = resp.data;
          }).catch(error => {
            console.log(error);
          }); 
      },
    }
  }
</script>

As you can see, you don't need a renderHtml method at all, as vue does the work for you.

By the way: I recommend you to use async/await instead of .then. It in my opinion makes your code cleaner and look more professional.

CodePudding user response:

Have you tried v-html?

Documentation: https://br.vuejs.org/v2/guide/syntax.html#HTML

  • Related