Evan You 10 лет назад
Родитель
Сommit
03804cefa7

+ 1 - 1
src/compiler/codegen/index.js

@@ -159,7 +159,7 @@ function genText (text) {
   } else {
     const exp = parseText(text)
     if (exp) {
-      return `(exp==null?'':String(${exp}))`
+      return `(${exp}==null?'':String(${exp}))`
     } else {
       return JSON.stringify(text)
     }

+ 16 - 0
src/runtime/instance/state.js

@@ -15,6 +15,7 @@ export function initState (vm) {
   initData(vm)
   initComputed(vm)
   initMethods(vm)
+  initWatch(vm)
 }
 
 function initData (vm) {
@@ -92,6 +93,21 @@ function initMethods (vm) {
   }
 }
 
+function initWatch (vm) {
+  const watch = vm.$options.watch
+  if (watch) {
+    for (let key in watch) {
+      let handler = watch[key]
+      let options
+      if (typeof handler === 'object') {
+        handler = handler.handler
+        options = handler
+      }
+      vm.$watch(key, handler, options)
+    }
+  }
+}
+
 export function stateMixin (Vue) {
   Object.defineProperty(Vue.prototype, '$data', {
     get () {

+ 9 - 4
src/runtime/observer/watcher.js

@@ -6,6 +6,7 @@ import {
   extend,
   isArray,
   isObject,
+  parsePath,
   _Set as Set
 } from '../util/index'
 
@@ -52,10 +53,14 @@ export default function Watcher (vm, expOrFn, cb, options) {
   if (isFn) {
     this.getter = expOrFn
   } else {
-    this.getter = function () {}
-    process.env.NODE_ENV !== 'production' && warn(
-      'Watcher only accpets function.'
-    )
+    this.getter = parsePath(expOrFn)
+    if (!this.getter) {
+      this.getter = function () {}
+      process.env.NODE_ENV !== 'production' && warn(
+        'Watcher only accepts simple dot-delimited paths. ' +
+        'For full control, use a function instead.'
+      )
+    }
   }
   this.value = this.lazy
     ? undefined

+ 20 - 0
src/runtime/util/lang.js

@@ -312,3 +312,23 @@ export function def (obj, key, val, enumerable) {
     configurable: true
   })
 }
+
+/**
+ * Parse simple path.
+ */
+
+const bailRE = /[^\w\.]/
+export function parsePath (path) {
+  if (bailRE.test(path)) {
+    return
+  } else {
+    path = path.split('.')
+    return function (obj) {
+      for (let i = 0; i < path.length; i++) {
+        if (!obj) return
+        obj = obj[path[i]]
+      }
+      return obj
+    }
+  }
+}