1. // 入口
    2. // 当 options 中有 watch,并且 watch 不等于有些浏览器上(火狐)自带的 watch,则视为有效的 watch,进行初始化
    3. if (opts.watch && opts.watch !== nativeWatch) {
    4. initWatch(vm, opts.watch)
    5. }
    6. function initWatch (vm: Component, watch: Object) {
    7. // 遍历循环,通过 $watch 创建
    8. for (const key in watch) {
    9. const handler = watch[key]
    10. if (Array.isArray(handler)) {
    11. for (let i = 0; i < handler.length; i++) {
    12. createWatcher(vm, key, handler[i])
    13. }
    14. } else {
    15. createWatcher(vm, key, handler)
    16. }
    17. }
    18. }
    19. function createWatcher (
    20. vm: Component,
    21. expOrFn: string | Function,
    22. handler: any,
    23. options?: Object
    24. ) {
    25. if (isPlainObject(handler)) {
    26. options = handler
    27. handler = handler.handler
    28. }
    29. if (typeof handler === 'string') {
    30. handler = vm[handler]
    31. }
    32. return vm.$watch(expOrFn, handler, options)
    33. }