Search code examples
htmlvuejs2axiosdynamic-html

How can I display dynamic HTML having Vue variables inside?


I am trying to make the page content dynamic. I am using ck-editor in which i added html content and used the same vue variables inside it which i declared in the vue file where i want to show ck-editor data. I found a similar post vuejs - “editing” html inside variable which works fine if i write the html inside a variable. But in my case, i am saving data in database. It is saving properly with html tags, without converting the tags. When i get data using axios it returns it in form of string. And i used vue variable to display that html.

Here is my code for better understanding:

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

new Vue({
  el: '#app',
  created() {
    this.getSalesContent();
  },
  data: {
    salesContent: '',
    pageName: 'Sales',
    salesNumber: '987-586-4511'
  },
  computed: {
    htmlText() {
      return `${this.salesContent}`;
      //return this.salesContent;
    }
  },
    methods: {
      getSalesContent(){
        axios.get('api/Sales').then(({ data }) => {  // getting data from DB
          this.salesContent = data.sales; //data.sales have this.pageName and this.salesNumber variables
        });
      }
    }
});

Here is the example of data saved in db:

<p style="font-weight:bold"><span style="color:red">{{pageName}}</span>,</p>

<p style="font-weight:bold"><span style="color:red">${this.pageName} ${this.pageName}</span></p>

<p style="font-weight:bold">Contact Sales at ${this.salesNumber}  {{salesNumber}}</span></p>

I used variables in all possible ways. But on the page they are printing in it the same way i saved it. Here is the output:

screenshot

Can anyone help me make it working.

Thanks in Advance.


Solution

  • IMHO since the salesContent is fetched from db, it's a plain String. Thus nor vuejs or vanilla javascript will replace the inline variables with their values. (It may be possible by using eval, but it's totally out of question...) You should manually do that with String replace function. Like the following:

    <p style="font-weight:bold"><span style="color:red">{{pageName}}</span>,</p>
    
    <p style="font-weight:bold">Contact Sales at {{salesNumber}}</span></p>
    
    methods: {
          getSalesContent(){
            axios.get('api/Sales').then(({ data }) => {  // getting data from DB
              let salesContent = data.sales; //data.sales have this.pageName and this.salesNumber variables
              salesContent = salesContent.replace(/{{pageName}}/g, this.pageName)
              salesContent = salesContent.replace(/{{salesNumber}}/g, this.salesNumber)
              this.salesContent = salesContent
            });
          }
        }