Vue: 可以提供对集合数据变化的$watch 吗?

Created on 1 Nov 2015  ·  7Comments  ·  Source: vuejs/vue

目前提供的deep参数只是针对当个对象的多个属性,在实际的应用开发中会涉及到对多行数据的统一提交,这就需要对集合数据变化的监听,对于集合数据的监听,大致需要这几个参数:当前对象(model)、更改的属性名(name)、更改值(newValue)、更改前值(oldValue)。
我用遍历方式来逐一绑定对象的watch,我换了好几种方法都不能监听到数据的变化!
谢谢!

Most helpful comment

这样循环是可以工作,但是属性名传不进去啊, 取得了最新值和旧值,但不知道是哪个属性了。

All 7 comments

『多行数据的统一提交』具体是什么?上代码。为什么一定要对集合数据监听才能解决你的问题?没讲清楚。

背景说明:多行数据的统一提交,是指基于表格的数据编辑,前端需要知道哪些数据做了修改,那么提交时只提交修改部分的就可以。
代码要点:
1、html,smart-table 是自定义的指令,封装了表格数据的操作。

    <smart-table class="table table-condensed" :row-num="true" :multi-select="false"         :columns="columns"   :data="rows" :pager="false">
   </smart-table>

2、javascript 代码,rows是需要检测变化的集合。

  data: function () {
    return{
      rows:[]
    }

3、需求:在代码中需要实时获取到修改的行或字段值,以便提交时只提交修改的部分。
4、目前的尝试,代码有问题(捕获不了$watch变化,就是 走不到console.log("fire!")这里)

      var self = this;
     _.forEach(this.rows,function(row){
        self.vm.$watch(row, function (value, oldValue) {
         console.log("fire!")
        }, {immediate: true, deep: true })
     });

谢谢!

请仔细看看 $watch 的 API 文档: http://vuejs.org/api/#vm-watch

只接受 expression 或 function。你传个对象进去没有用的。

改成expression和function后,还是不能捕获变更!
写法1:

  _.forEach(this.rows,function(row){
        self.vm.$watch(
         function () {
               return row;
         },
        function (newValue, oldValue)
                         console.log(newValue);
         },
         {
          deep:true
         })});              

写法2(只监测第一行数):

   self.vm.$watch(
        function () {
            return self.rows[0];
            },
        function (newValue, oldValue) {
            console.log(newValue);
         },{deep:true });

写法3(只监测第一行数,表达式写法):

    self. vm.$watch('rows[0]', function(newValue,oldValue){
                console.log(newValue);
      }, {deep: true});
var self = this
this.rows.forEach(function (row, i) {
  self.$watch('rows[' + i + ']', function () { /* ... */}, { deep: true })
})

更好的办法是做一个 row 组件,每一个 row 组件 watch 自己的对象。

代码可以正常工作了,还是强烈建议增加对集合数据的监测,在callback可以获取到:当前对象(model)、更改的属性名(name)、更改值(newValue)、更改前值(oldValue)。
非常感谢!

这样循环是可以工作,但是属性名传不进去啊, 取得了最新值和旧值,但不知道是哪个属性了。

Was this page helpful?
0 / 5 - 0 ratings

Related issues

robertleeplummerjr picture robertleeplummerjr  ·  3Comments

aviggngyv picture aviggngyv  ·  3Comments

guan6 picture guan6  ·  3Comments

paceband picture paceband  ·  3Comments

loki0609 picture loki0609  ·  3Comments