From fb3cc2be78779d5aba60ea2b3abd4722997c734c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Krystian=20Wola=C5=84ski?= Date: Fri, 28 Aug 2020 10:50:34 +0200 Subject: [PATCH] Add WatchPaths decorator --- src/vue-property-decorator.ts | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/src/vue-property-decorator.ts b/src/vue-property-decorator.ts index 2e2e159..31d9b8e 100644 --- a/src/vue-property-decorator.ts +++ b/src/vue-property-decorator.ts @@ -254,6 +254,34 @@ export function Watch(path: string, options: WatchOptions = {}) { }) } +/** + * decorator of a watch function for elements of an array + * @param paths the paths or the expression to observe + * @param WatchOption + * @return MethodDecorator + */ +export function WatchPaths(paths: string[], options: WatchOptions = {}) { + const { deep = false, immediate = false } = options; + + return createDecorator((componentOptions, handler) => { + if(typeof componentOptions.watch !== 'object') { + componentOptions.watch = Object.create(null); + } + + const watch: any = componentOptions.watch; + + paths.forEach(path => { + if(typeof watch[path] === 'object' && !Array.isArray(watch[path])){ + watch[path] = [watch[path]]; + }else if(typeof watch[path] === 'undefined') { + watch[path] = []; + } + + watch[path].push({handler, deep, immediate}); + }); + }); +} + // Code copied from Vue/src/shared/util.js const hyphenateRE = /\B([A-Z])/g const hyphenate = (str: string) => str.replace(hyphenateRE, '-$1').toLowerCase()