VueJs动态模板渲染

时间:2019-08-28 16:04:31

标签: vue.js vue-component

这是一个众所周知的问题,当您将HTML附加到包含其他vue组件的DOM时,可以选择仅将它们作为HTML插入,还可以在html中呈现组件。但是我找不到将其附加到同一父级的解决方案,它的行为就像一个单独的实例。

我创建了一个我要达到的目标的示例。

<div id="app">
  <button @click="clicked">
      Load greeting
  </button>
  <div id="inserted" v-html="internalHtml"></div>

  <!-- <greeting @clicked="greetingClicked"></greeting> -->
</div>

const Greeting = Vue.component('greeting', {
  template: '<p>Hi, dude! <br/><button @click="clicked">Click me!</button> </p>', 
  methods: {
    clicked() {
        this.$emit('clicked');
    }
  }
});

const LoadedHtml = 'This is a greating: <greeting @clicked="greetingClicked"></greeting>';

var vm = new Vue({
  el: '#app',
  data() {
    return {
            internalHtml: ''    
    }
  },
  methods: {
    clicked() {
         this.internalHtml = LoadedHtml;
       this.$nextTick(function(){
            new Vue({el: '#inserted'} );
       });
    },
    greetingClicked() {
        alert('Boo!');
    }
  }
});

提琴:https://jsfiddle.net/relaximus/znh3svy7/29/

警报“嘘!”必须在单击“单击我”后出现。 我将不胜感激。

1 个答案:

答案 0 :(得分:0)

您可以通过动态组件来实现:https://vuejs.org/v2/guide/components.html#Dynamic-Components

使用您的示例:https://jsfiddle.net/dqws96mr/1/

const Greeting = Vue.component('greeting', {
  template: '<p>Hi, dude! <br/><button @click="clicked">Click me!</button> </p>', 
  methods: {
    clicked() {
        this.$emit('clicked');
    }
  }
});

var vm = new Vue({
  el: '#app',
  data() {
    return {
            myDynamicComponent: null
    }
  },
  methods: {
    clicked() {
         this.myDynamicComponent = 'greeting'
    },
    greetingClicked() {
        alert('Boo!');
    }
  }
});