[Vuejs]-Can you dynamically define properties in a template string in Vuejs?

6๐Ÿ‘

โœ…

You can specify the data in the same way you specify the template: just interpolate it into the component spec.

new Vue({
  el: '#vue',
  data() {
    return {
      string: undefined,
      dataObj: undefined
    }
  },
  created() {
    //setTimeout to simulate ajax call
    setTimeout(() => {
      this.string = '<div><h1 v-for="n in 1">Hello!</h1><input v-model="message" placeholder="edit me"><p>Message is: {{ message }}</p></div>';
      this.dataObj = {
        message: 'initial'
      };
    }, 1000)
  }
})
<script src="//unpkg.com/vue@latest/dist/vue.js"></script>
<div id="vue">
  <component :is="string && {template:string, data: function() { return dataObj}}" />
</div>
๐Ÿ‘คRoy J

0๐Ÿ‘

You can use Props, but I am not sure if this is the best way to do it ๐Ÿ™‚ here is an example:

new Vue({
    el:'#vue',
    data(){
    return {
        string:undefined,
      message:''
    }
  },
  created(){
    //setTimeout to simulate ajax call
    setTimeout(()=> this.string = '<div><h1 v-for="n in 1">Hello!</h1><input v-model="message" placeholder="edit me"><p>Message is: {{ message }}</p></div>', 1000)
  }
})
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.13/dist/vue.min.js"></script> 
<div id="vue">
  <component :is="string && {template:string, props:['message']}" :message="message"/>
</div>
๐Ÿ‘คMohd_PH

0๐Ÿ‘

It looks like what you want is a component with a <slot> that you can dump a custom component into. If youโ€™re trying to compose components thatโ€™s probably the easiest way to do it.

Leave a comment