$watch
$watch 可用于监听特定属性的变化。当属性变化时,会执行传入的回调函数,回调函数会接收到新的属性值和原属性值。
参数
- key
string | Array<string>- 用于查找特定属性值,仅接受用
.分割的字符串。
- handler
Function- 当产生变化的时候会执行的函数
- 接受两个参数
newVal和oldVal,分别代表新旧属性值。但是在deep模式下对子元素的修改不会保存两份快照。
option
Object- 可选项
- 内容包括
- deep
boolean- 是否深度监听,可用于监听
Object和Array内部变量的变化。但是某些情况下需要配合$set和$del使用 - 默认为
false
- diff
boolean- 是否需要比对。如果为
false,只要有对属性的相关设置就会执行回调函数。 - 默认为
true
- other
Object | Array<*>- 在寻找属性的时候,一般会从所在实例本身上寻找,加入需要监听其他实例的属性,可以穿入该参数。
- 默认为
undefined
- proxy
- deep
unwatch
Function- 函数用于解绑监听函数,执行后,变化不会再调用回调函数
例子:
你可以轻易监听 video 上的一些属性。
import Chimee from 'chimme';const plugin = {name: 'plugin',create () {this.$watch('controls', (newVal, oldVal) => console.log(newVal, oldVal));}}Chimee.install(plugin);const player = new Chimee({wrapper: 'body',plugin: ['plugin']});player.controls = true; // true, false
又或者自定义属性:
import Chimee from 'chimme';const plugin = {name: 'plugin',data: {test: 1}create () {this.$watch('test', (newVal, oldVal) => console.log(newVal, oldVal));}}Chimee.install(plugin);const player = new Chimee({wrapper: 'body',plugin: ['plugin']});player.plugin.test = 2; // 2, 1
你也可以深度监听数组,直接调用数组的操作方法:
import Chimee from 'chimme';const plugin = {name: 'plugin',data: {test: [1, 2, 3]}create () {this.$watch('test', (newVal, oldVal) => console.log(newVal, oldVal), {deep: true});}}Chimee.install(plugin);const player = new Chimee({wrapper: 'body',plugin: ['plugin']});player.plugin.test.push(4); // [1, 2, 3, 4], [1, 2, 3, 4]
同理你也可以深度监听对象,但是对新增元素或者删除元素需要使用 $set 和 $del 进行辅助。
import Chimee from 'chimme';const plugin = {name: 'plugin',data: {test: {foo: 1}}create () {this.$watch('test', (newVal, oldVal) => console.log(newVal, oldVal), {deep: true});}}Chimee.install(plugin);const player = new Chimee({wrapper: 'body',plugin: ['plugin']});player.plugin.test.foo = 2; // {foo: 2}, {foo: 2}player.$set(test, 'bar', 1); // {foo: 2, bar: 1}, {foo: 2, bar: 1}player.$del(test, 'bar'); // {foo: 2}, {foo: 2}
注意:- 并非所有 video 相关属性都可以监听。现阶段只支持监听$videoConfig 中除src以外的部分。src的值因为涉及到 video 播放核心的变换,以及事件拦截等,建议采取事件驱动模式编写。paused等 video 只读属性,因为需要监听原生 video,故暂不提供。且以上属性大部分可以通过事件获取。- 采取深度监听时,子元素修改后回调函数并不会获得原有对象快照- 深度监听时需要使用$set和$del进行辅助。