[Vuejs]-Vue.js render ajax data that contains vue.js syntax

0👍

Sounds like you want to use an Async Component.

Something like…

components: {
  'async-media': () => Vue.http.get('/media').then(res => ({
    template: res.body,
    methods: {
      alertVideoLink (event) {
        this.$emit('click', event)
      }
    }
  }))
}

Then in your template…

<async-media @click="handleClickEventFromChildComponent" />

Here’s an example using a timeout to fake "load" a template

var app = new Vue({
  el: '#app',
  data: {},
  components: {
    'async-media': () => new Promise(resolve => {
      setTimeout(() => {
        resolve({
          template: '<a href="/media/videos" @click.prevent.self="alertVideoLink($event)">Video Link</a>',
          methods: {
            alertVideoLink(event) {
              this.$emit('click', event.target.href)
            }
          }          
        })
      }, 2000)
    })
  },
  methods: {
    handleClickEventFromChildComponent (href) {
      console.info('Clicked on', href)
    }
  }
});
<div id="app">
  <p>Wait 2 seconds</p>
  <async-media @click="handleClickEventFromChildComponent" />
</div>
<script src="https://unpkg.com/vue@2.4.2/dist/vue.min.js"></script>

0👍

@Phil’s answer is correct but in my project need to be changed. in this case, the better way is: using global components vs local components because is simple for this work.

Leave a comment