【问题标题】:Vue js Bind dynamic id when adding text box dynamically on button clickVue js在按钮单击时动态添加文本框时绑定动态ID
【发布时间】:2019-03-22 07:59:19
【问题描述】:

我可以在按钮点击时动态添加文本框。我的问题是我无法设置动态 ID 和值。

<div id="app">
        <div>
            <button class="button btn-primary" @click="addRow">Add row</button>
        </div>
        <div v-for="row in rows">
            <button-counter></button-counter>
        </div>
    </div>       
    <script>    
        Vue.component('button-counter', {
            template: '<input type="text" style="margin-top: 10px;" ><br>'
        })    
        var app = new Vue({
            el: "#app",
            data: {
                rows: [],
                count:0              
            },
            methods: {
                addRow: function () {
                    var txtCount=++this.count;
                    id='txt_'+txtCount;
                    this.rows.push({ title: "first", description: "textbox1" });
                }
            }
        });

    </script> 


  This is my code.

我在组件上创建了输入并创建了一个 vue 实例。单击添加行按钮时,它将添加一个新的文本框。但我不知道为文本框绑定 id 和值。

【问题讨论】:

    标签: javascript vue.js vuejs2 vue-component


    【解决方案1】:

    你可以在 rows 数组中传递 id

    <div v-for="row in rows" :id=row.id>
      <button-counter></button-counter>
    </div>
    

    并在添加新行时传递 id

    this.rows.push({ title: "first", description: "textbox1", id });
    

    【讨论】:

    • 它会抛出一个警告:Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders.
    【解决方案2】:

    您可以在 rows 项目中添加 id 并将其用作 id。但我假设您这样做是为了稍后可以检索输入值。有更好的方法来做到这一点。

    在您的父数据对象上定义一个values 对象。像这样:

    data: {
      rows: [],
      values: {},
      count:0              
    },
    

    每次添加新行时,都会为其添加一个响应式属性:

    addRow: function () {
      var txtCount=++this.count;
      id='txt_'+txtCount;
      this.rows.push({ title: "first", description: "textbox1"});
      this.$set(this.values, id, '')
    },
    

    在您的自定义组件上定义一个 value 属性,并在每次值更改时发出一个 input 事件。让您的自定义组件准备好接收v-model

    Vue.component('button-counter', {
     props: ['value'],
     template: '<input type="text" @input="$emit(\'input\', 
      arguments[0].srcElement.value)" style="margin-top: 10px;" ><br>'
    }) 
    

    将每个自定义组件绑定到正确的v-model

    <button-counter v-model='values[row.id]'></button-counter>
    

    现在您可以访问父组件中values 中的所有输入值。

    这是一个有效的jsfiddle。

    顺便说一句:您遇到错误是因为您的自定义组件有多个根。您需要删除 br 或添加包装元素。

    【讨论】:

      【解决方案3】:

      好吧,首先为了识别每个输入元素,您需要将:key attr 添加到v-for

      要绑定值,您可以在创建输入元素时将 value 和 id 作为 prop 传递,并将值传递给输入类型的 v-model,因此无论何时创建它,您都可以将其包含在输入中。

      这里是JsFiddle

      希望这会有所帮助!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-11-09
        • 2013-07-09
        • 2011-12-17
        • 2011-12-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多