我可以传递模板字符串,也可以动态传递属性,以便使其具有反应性吗?在下面的示例中,我希望消息是被动的,但是我不想在data选项中预先定义它。

<div id="vue">
 <component :is="string && {template:string}"/>
</div>

new Vue({
    el:'#vue',
    data(){
    return {
    string: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>', 1000)
  }
})


https://jsfiddle.net/kxtsvtro/5/

最佳答案

您可以用指定模板的相同方式指定data:只需将其内插到组件规范中即可。



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>

09-16 19:43