瀏覽代碼

feat: add Vue.observable() for explicitly creating observable objects

Evan You 7 年之前
父節點
當前提交
c50bbde41c
共有 2 個文件被更改,包括 37 次插入0 次删除
  1. 7 0
      src/core/global-api/index.js
  2. 30 0
      test/unit/features/global-api/observable.spec.js

+ 7 - 0
src/core/global-api/index.js

@@ -8,6 +8,7 @@ import { initAssetRegisters } from './assets'
 import { set, del } from '../observer/index'
 import { ASSET_TYPES } from 'shared/constants'
 import builtInComponents from '../components/index'
+import { observe } from 'core/observer/index'
 
 import {
   warn,
@@ -44,6 +45,12 @@ export function initGlobalAPI (Vue: GlobalAPI) {
   Vue.delete = del
   Vue.nextTick = nextTick
 
+  // 2.6 explicit observable API
+  Vue.observable = (obj: any): any => {
+    observe(obj)
+    return obj
+  }
+
   Vue.options = Object.create(null)
   ASSET_TYPES.forEach(type => {
     Vue.options[type + 's'] = Object.create(null)

+ 30 - 0
test/unit/features/global-api/observable.spec.js

@@ -0,0 +1,30 @@
+import Vue from 'vue'
+
+describe('Global API: observable', () => {
+  it('should work', done => {
+    const state = Vue.observable({
+      count: 0
+    })
+
+    const app = new Vue({
+      render(h) {
+        return h('div', [
+          h('span', state.count),
+          h('button', {
+            on: {
+              click: () => {
+                state.count++
+              }
+            }
+          }, '+')
+        ])
+      }
+    }).$mount()
+
+    expect(app.$el.querySelector('span').textContent).toBe('0')
+    app.$el.querySelector('button').click()
+    waitForUpdate(() => {
+      expect(app.$el.querySelector('span').textContent).toBe('1')
+    }).then(done)
+  })
+})