是否可以在按钮上附加组件?

时间:2017-06-16 18:44:46

标签: javascript vue.js vue-component

这是我想要解决的问题: 我有一个按钮,按下时必须将 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>

1 个答案:

答案 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/vue@2.2.6/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/vue@2.2.6/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>

代码定义了一个表单对象,并迭代表单的属性以呈现每个属性的输入。

这显然非常幼稚,只处理输入文本等。但希望你明白这一点。