【问题标题】:Binding to array fields in vue.js绑定到 vue.js 中的数组字段
【发布时间】:2019-02-09 03:09:30
【问题描述】:

我想在表格行中创建多个“就地”可编辑日期字段。 以下单个字段的示例有效。 我将当前日期(旧日期)显示为标签。用户点击“更改”,出现输入框,编辑后用户可以接受或取消。

https://jsfiddle.net/asrajan55/qv6crg84/

<div id="root">
    <label>Test Date:</label>
    <span v-show="!makeEditable"> {{ oldDate }} </span>
    <span v-show = "makeEditable">

        <input type="date" v-model="newDate" required=""/>
        <button @click="acceptClicked">Accept</button>
        <button name="cancel" @click="makeEditable=false">Cancel</button>
    </span>
    <button v-show="!makeEditable" @click="makeEditable=true" >Change</button>
  </div>

  new Vue({
      el: "#root",
      data: {
        oldDate: '2019-02-04',
        newDate: '2019-02-04',
        makeEditable: false,
      },

      methods: {
        acceptClicked(){
          if (this.newDate!='') {
            this.oldDate=this.newDate;
            this.makeEditable=false;
          }
        }
      }
   });

但是,如果我尝试多个(2)字段,点击事件(有时)会触发,但似乎没有任何反应。控制台没有错误。此外,浏览器中的 Vue 调试器不会立即更新更改的字段。请帮忙。我绝望了,把我的头发拔了出来!

https://jsfiddle.net/asrajan55/9uhkr4w0/3/

<div id="root">
    <div v-for="(item,index) in oldDates">
        <label for="">Test Date:</label>
        <span v-show="!editables[index]">{{item}}</span>
        <input v-show="editables[index]" type="date" v-model="oldDates[index]"/>
        <button v-show="editables[index]">Accept</button>
        <button v-show="editables[index]" @click="editables[index]=false">Cancel</button>
        <button v-show="!editables[index]" @click="makeEditable(index)">Change</button>
        <hr />
    </div>

</div>

new Vue({
    el: "#root",
    data: {
        oldDates: ['2019-01-04', '2019-02-04'],
        newDates: ['2019-01-04', '2019-02-04'],
        editables: [false, false]
    },

    methods: {
        makeEditable(index) {
            alert(index);
            this.editables[index] = true;
        }
    }
});

【问题讨论】:

    标签: vue.js


    【解决方案1】:

    问题是你在原地改变数组, 创建一个新的数组引用并传递它可以解决问题

    固定在这里:https://jsfiddle.net/e3L2zcna/

    makeEditable(index) {
          this.editables = this.editables.map((val,i) => i===index || val);
        }
    

    【讨论】:

      【解决方案2】:

      尝试使用 this.$set(this.editables, index, true);

      如果您使用 [] 直接访问元素,Vue 无法检测到数组的更改。在此处阅读:

      https://vuejs.org/2016/02/06/common-gotchas/#Why-isn%E2%80%99t-the-DOM-updating

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-09-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-22
        • 2021-02-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多