Skip to content Skip to sidebar Skip to footer

Can You Dynamically Define Properties In A Template String In Vuejs?

Can I pass in a template string and also dynamically pass in a property so that I can make it reactive? In the example below I would like message to be reactive, but I don't want t

Solution 1:

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>

Solution 2:

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>

Solution 3:

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.


Post a Comment for "Can You Dynamically Define Properties In A Template String In Vuejs?"