Dynamically adding different components in Vue

前端 未结 3 1826
时光说笑
时光说笑 2021-02-02 01:22

I want to create a simple form builder with Vue where users click on buttons from a menu to add different form fields to a form. I know that if there was just one type of form f

3条回答
  •  滥情空心
    2021-02-02 02:02

    Based on the code from the answer, one could add dynamic content for each one of those form controls as well ( the full concept could be seen from the following site):

       Vue.component('form-input', {
      template: '#form-input'
      , props: ['label','cnt']
       });
    
    Vue.component('form-select', {
     template: '#form-select'
     , props: ['label','cnt']
    });
    
    Vue.component('form-textarea', {
       template: '#form-textarea'
       , props: ['label','cnt']
       });
    new Vue({
      el: '#app',
      data: {
        fields: [],
        count: 0
      }
      , mounted() {
        // fetch those from back-end
        this.addFormElement('form-input','lbl', "form-input-content")
        this.addFormElement('form-textarea','lbl', "form-textarea-content")
        var select_cnt = [
          {'value': 1, 'text': 'item-01'},
          {'value': 2, 'text': 'item-02'}
        ]
        this.addFormElement('form-select','some-label',select_cnt)
      }
      , methods: {
        addFormElement: function(type,label,cnt) {
         this.fields.push({
           'type': type
           , id: this.count++
           , 'label':label
           , 'cnt':cnt
         });
       }
      }
    })
    
    

提交回复
热议问题