1. 程式人生 > >【Html】Vue動態插入組件

【Html】Vue動態插入組件

emp pre b- add AR com HR 動態 []

html:

<div id="app">
  <p>{{ message }}</p>
  <button @click="add(‘a-component‘, ‘我是A‘)">添加A組件</button>
  <button @click="add(‘b-component‘, ‘我是B‘)">添加B組件</button>
  <component :is="item.component" :text="item.text" v-for="item in items"></component>
</div>

js:

<script>
const aComponent = Vue.extend({
  props: [‘text‘],
  template: ‘<li>A Component: {{ text }}</li>‘
})

const bComponent = Vue.extend({
  props: [‘text‘],
  template: ‘<li>B Component: {{ text }}</li>‘
})

new Vue({
  el: ‘#app‘,
  data () {
    
return { message: ‘Hello Vue.js!‘, items: [] } }, methods: { add (name, text) { this.items.push({ component: name, text: text }) } }, components: { aComponent, bComponent } })
</script>

重點是使用了:

Vue.extend

查看實例:

https://codepen.io/kakarrot2009/pen/VxLOrQ

【Html】Vue動態插入組件