vue-watch 数组或者对象

本贴最后更新于 1794 天前,其中的信息可能已经东海扬尘

很多时候我们需要监听数据,可能是路由,类型可能会是字符串,数组,对象,整理了下几种监听的方式。

普通的 watch

data() {
    return {
        frontPoints: 0    
    }
},
watch: {
    frontPoints(newValue, oldValue) {
        console.log(newValue)
    }
}

数组的 watch

data() {
    return {
        winChips: new Array(11).fill(0)   
    }
},
watch: {
  winChips: {
    handler(newValue, oldValue) {
      for (let i = 0; i < newValue.length; i++) {
        if (oldValue[i] != newValue[i]) {
          console.log(newValue)
        }
      }
    },
    deep: true
  }
}

对象的 watch

data() {
  return {
    bet: {
      pokerState: 53,
      pokerHistory: 'local'
    }   
    }
},
watch: {
  bet: {
    handler(newValue, oldValue) {
      console.log(newValue)
    },
    deep: true
  }
}

只要 bet 中的属性发生变化(可被监测到的),便会执行 handler 函数;

如果想监测具体的属性变化,如 pokerHistory 变化时,才执行 handler 函数,则可以利用计算属性 computed 做中间层。

事例如下:

对象具体属性的 watch[活用 computed]

data() {
  return {
    bet: {
      pokerState: 53,
      pokerHistory: 'local'
    }   
    }
},
computed: {
  pokerHistory() {
    return this.bet.pokerHistory
  }
},
watch: {
  pokerHistory(newValue, oldValue) {
    console.log(newValue)
  }
}
  • Vue.js

    Vue.js(读音 /vju ː/,类似于 view)是一个构建数据驱动的 Web 界面库。Vue.js 的目标是通过尽可能简单的 API 实现响应的数据绑定和组合的视图组件。

    261 引用 • 662 回帖

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...