簡體   English   中英

如何將v模型添加到組件中動態添加的html輸入中

[英]How to add v-model to html input dinamically added in component

我有這個組件,然后,在異步請求之后,我需要創建一個新輸入並對其進行v模型投標,這可能嗎?

<template>
  <div>
    <div id="newInputsWrapper">
    </div>
  </div>
</template>

<script>
export default {
  data () {
    return {
      foo:''
    }
  },
  mounted () {
    //Simulating asynchronous request
    setTimeout(function(){
    document.getElementById('newInputsWrapper').innerHTML = '<input type="text" v-model="hereAnymodel">'
    //....maybe I will need to add more generated inputs...
    },2000);
  }
}
</script>

<style>
</style>

在Vue中,您不會使用選擇器來修改html / template,至少在通常情況下不會如此。 使您的異步請求修改組件中的變量。 然后使用that變量在模板中渲染內容。

你會得到這樣的東西。 在這里,我們使用一些標簽和ID填充fields變量。 這些ID映射到名為form表單數據變量。 我們填充它以防止不存在的變量上的v-model時髦。 以后我們可以使用form變量來做所有事情。

<template>
  <div>
    <h2>All kind of things</h2>

    <template v-for="field in fields">
      <label :key="field.id">{{ field.label }} <input type="text" v-model="form[field.id]" /></label>
    </template>
  </div>
</template>

<script>
export default {
  data() {
    return {
      fields: [],
      form: {}
    };
  },

  watch: {
    fields(fields) {
      for (const field of fields) {
        if (this.form[field.id] === undefined) {
          this.$set(this.form, field.id, "");
        }
      }
    },

    form: {
      deep: true,
      handler(newForm) {
        console.log("Looks like our data has been changed!", newForm);
      }
    }
  },

  mounted() {
    //Simulating asynchronous request
    setTimeout(() => {
      this.fields = [
        { id: "a", label: "Label a" },
        { id: "b", label: "Label b" },
        { id: "c", label: "Label c" },
        { id: "d", label: "Label d" }
      ];
    }, 2000);
  }
};
</script>

<style>
label {
  display: block;
}
</style>

編輯Vue模板

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM