请参考我下面的片段.如何获取更改模型的旧值,在本例中是vuejs中的年龄?

var app = new Vue({
  el:"#table1",
  data:{
   items:[{name:'long name One',age:21},{name:'long name Two',age:22}]
  },
  methods:{
    changeAge:function(item,event){
      alert(item.age);
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://unpkg.com/vue/dist/vue.js"></script>

<table class="table table-cart" id="table1">
   <thead>
     <tr>
       <th>Name</th>
       <th>Age</th>
     </tr>
  </thead>
   <tbody>
     <tr v-for="(item,index) in items">
       <td>{{item.name}} :</td>       
       <td>
         <input type="text" name="qty"
                v-model="item.age"   
                @change="changeAge(item,$event)">
       </td>
     </tr>
   </tbody>
 </table>

我试着用手表,但在观察一系列物品的年代时,我找不到任何帮助.

推荐答案

This solution assumes that you need the old value only when handling the change coming from user input - which is probably the case, and not a generic model change. Below I added a sketch of solution watching all changes in if it's necessary, though perhaps it's better to control the other changes at the places they occur, and not in this component.

Drop v-model and replace it with manual handling.

重要的是要注意"although a bit magical, v-model is essentially syntax sugar for updating data on user input events (...)".因此,在不造成太大伤害的情况下,您可以删除它并直接处理事件,就像您几乎已经做过的那样.

首先,用:value代替v-model.输入仍将跟随item.age次更新,但不会自动更新年龄.

<input type="text" name="qty"
       :value="item.age"
       @change="changeAge(item,$event)">

然后,为了实际更新该值,将item.age = event.target.value添加到changeAge,如下所示:

changeAge: function(item, event){
  alert(item.age);  // Old value
  alert(event.target.value);  // New value
  item.age = event.target.value;  // Actual assignment
}

Note: you may want to use @input instead, that's what v-model actually uses.

就这样,它应该会起作用.如果需要防止更改,可以省略赋值,但是需要重置输入值.Vue.set(item, 'age', item.age)人中的item.age = item.age人可能会成功,但我不太确定它会成功.

注意:event.target.value是一个字符串,如果需要数字,请使用parseInt().

for each 项目创建一个单独的组件实例,并在其中创建一个手表

In case you need to watch all the changes. However, if you need that, perhaps you should do that in some other place, not this component.

我还没有准备好所有的细节,所以我将只是一个大致的草稿:在v-for中,而不是普通的<input>中,放置另一个组件,比如<my-item>.你在上面加了v-model=item.在组件内部,创建<input>并将valueprops 转发给它,以及转发外部的input/change事件.在您的组件中,单个项目是单个props ,因此您可以将观察者直接连接到它.相关文件:Component BasicsCustomizing Component v-modelProps.

Vue.js相关问答推荐

复选框列未在vutify中排序

V-img不显示文件夹中的图像

Vuetify 2中自定义标头的排序和筛选

从组件中检索 Shopware CMS 编辑器中的自定义实体数据

在重复表行中

使用 Vue.js 和 Jest 进行 URL 重定向测试

如何在 Vue.js 中获取完整的当前日期和时间,而无需编写大量 JavaScript 行

在 vue.js 中获取当前时间和日期

如何将 ASP.NET Core 2.1 与 Vue CLI 3 集成?

v-for 中的 VueJS 插槽

Laravel 中的 VueJS 组件实现中的鼠标悬停

在 Vuejs 中计算 DOM 元素之间距离的最佳方法是什么?

Vuejs:我应该在 vue-router SPA 中的哪里放置一些常用的 js 工具?

try 通过 Vue.js 中的渲染传递props并观察它们

我应该将所有数据存储在 vuex 状态

在vue中单击时如何模糊元素

Vuejs 不会在 HTML 表格元素中呈现组件

Axios 捕获错误请求失败,状态码 404

Vue 3 – 渲染无法动画的非元素根 node

如何在 vuejs 中的基于类的组件中编写计算设置器