[Vuejs]-Data binding in fetched v-html content

1๐Ÿ‘

โœ…

If the template strings are not Vue templates then you could parse the {{ ... }} placeholders yourself using a RegExp.

new Vue({
  el: '#app',
  
  data () {
    return {
      firstName: 'John',
      lastName: 'Smith',
      title: 'Mr',
      template: 'Hi {{ title }} {{ firstName }} {{ lastName }}'
    }
  },
  
  computed: {
    templateOutput () {
      return this.template.replace(/{{\s*([\S]+?)\s*}}/g, (full, property) => {
        return escape(this[property])
      })
      
      function escape (str) {
        if (str == null) {
          return ''
        }
        
        return String(str)
          .replace(/&/g, '&')
          .replace(/>/g, '>')
          .replace(/</g, '&lt;')
          .replace(/"/g, '&#34;')
          .replace(/'/g, '&#39;')
      }
    }
  }
})
<script src="https://unpkg.com/vue@2.6.10/dist/vue.js"></script>

<div id="app">
  <div v-html="templateOutput"></div>
</div>
๐Ÿ‘คskirtle

Leave a comment