[Vuejs]-Passing custom emited events as props to a new created component in VueJs

0👍

In parent component, declare one data property=childs, it will includes all childs already created.

So once parent component receives the event=submit-to-vue, then add one new child to this.childs

Finally uses v-for to render these child components.

The trick: always consider the data-driven way, doesn’t manipulate dom directly as possible.

below is one simple demo :

Vue.config.productionTip = false

Vue.component('child', {

  template: `
  <div> 
    <div>Label:<span>{{output}}</span></div>
    <div>Value:<span>{{command}}</span></div>
    <div id="input-line" class="input-line">
        <div class="prompt">{{ prompt }}</div>
        <div>
        <input class="cmdline" autofocus 
            v-model.trim="command" 
            @keyup.enter="submit"  
            :readonly="submited" />
        </div>
    </div>
  </div>`,
  props: ['output'],
  data() {
    return {
      submited: false,
      command: ''
    }
  },
  computed: {
    prompt: function () {
      return this.submited ? 'Already submitted, input is ready-only now' : ''
    }
  },
  methods: {
    submit: function () {
      this.$emit('submit-to-vue')
      this.submited = true
    }
  }
})

app = new Vue({
  el: "#app",
  data: {
    childs: [{'output':'default:'}]
  },
  methods: {
    addChild: function () {
      this.childs.push({'output': this.childs.length})
    }
  }
})
<script src="https://unpkg.com/vue@2.5.16/dist/vue.js"></script>
<div id="app">
  <div>
    <ul>
      <li v-for="(child, index) in childs" :key="index">
        <child :output="child.output" @submit-to-vue="addChild()"></child>
      </li>
    </ul>
  </div>
</div>
👤Sphinx

Leave a comment