2017-06-16 19 views
1

下面是我想解決的一個問題: 我有一個按鈕,當按下按鈕時,必須將my-component附加到dom。 如果按下2次,則必須有2個<p> tegs。我怎樣才能做到這一點?是否可以在按鈕上追加組件?

JS:

<script> 

    Vue.component('my-component', { 
    template: "<p>hello</p>", 
    }) 

    var vue = new Vue({ 
    el: "#App", 
    data: {}, 
    methods: { 
     append: function() { 
     // unknown code here 
     } 
    } 
    }) 
</script> 

HTML:

<div id = "App"> 
    <button @click="append" class="btn btn-primary">Spawn stuff!</button> 
</div> 
+0

通常通過將一組數據呈現爲組件,然後將新項目推送到該數組。 –

回答

2

這裏是你能做到這一點的方法之一。此代碼使用v-foriterate over a range迭代計數器。

Vue.component('my-component', { 
 
    template: "<p>hello</p>", 
 
}) 
 

 
var vue = new Vue({ 
 
    el: "#App", 
 
    data: { 
 
    hellocount: 0 
 
    }, 
 
    methods: { 
 
    append: function() { 
 
     // unknown code here 
 
     this.hellocount++ 
 
    } 
 
    } 
 
})
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script> 
 
<div id="App"> 
 
    <my-component v-for="n in hellocount" :key="n"></my-component> 
 

 
    <button @click="append" class="btn btn-primary">Spawn stuff!</button> 
 
</div>

這是一個小非典型;通常你會從實際數據中驅動渲染的組件,就像@RoyJ在你的評論中所建議的那樣。

從您的評論下面,你可以建立一個這樣的形式。

Vue.component('my-input', { 
 
    props:["value", "name"], 
 
    data(){ 
 
    return { 
 
     internalValue: this.value 
 
    } 
 
    }, 
 
    methods:{ 
 
    onInput(){ 
 
     this.$emit('input', this.internalValue) 
 
    } 
 
    }, 
 
    template: ` 
 
    <div> 
 
     {{name}}:<input type="text" v-model="internalValue" @input="onInput"> 
 
    </div> 
 
    `, 
 
}) 
 

 
var vue = new Vue({ 
 
    el: "#App", 
 
    data: { 
 
    form:{ 
 
     name: null, 
 
     email: null, 
 
     phone: null 
 
    } 
 
    }, 
 
    methods:{ 
 
    append(){ 
 
     const el = prompt("What is the name of the new element?") 
 
     this.$set(this.form, el, null) 
 
    } 
 
    } 
 
})
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script> 
 
<div id="App"> 
 
    <my-input v-for="(value, prop) in form" 
 
      :key="prop" 
 
      v-model="form[prop]" 
 
      :name="prop"> 
 
    </my-input> 
 
    
 
    <button @click="append">Add New Form Element</button> 
 
    <div> 
 
    Form Values: {{form}} 
 
    </div> 
 
</div>

該代碼定義了一個表格對象和迭代形式的屬性來呈現每個屬性的輸入。

這顯然是非常天真的,只處理輸入文本等,但希望你明白了。

+0

我知道它可能聽起來有點不可思議,但最初我想弄清楚如何製作一個消耗性表單,這樣當按下按鈕時,用戶會看到額外的輸入字段以添加更多數據 –

+0

@JohnAward當然。您可以定義一個輸入定義數組並迭代它來添加輸入元素。 – Bert

+0

@JohnAward更新了第二個例子,你可能會這樣做。請注意,它僅僅是一個例子,並不包括大量的邊緣案例等。 – Bert

相關問題