From c50bbde41c4a1868a8a0b33df3238346840bd37c Mon Sep 17 00:00:00 2001 From: Evan You Date: Thu, 10 Jan 2019 16:03:03 -0500 Subject: [PATCH] feat: add Vue.observable() for explicitly creating observable objects --- src/core/global-api/index.js | 7 +++++ .../features/global-api/observable.spec.js | 30 +++++++++++++++++++ 2 files changed, 37 insertions(+) create mode 100644 test/unit/features/global-api/observable.spec.js diff --git a/src/core/global-api/index.js b/src/core/global-api/index.js index 03ffa0fbf31..2bca92bbf70 100644 --- a/src/core/global-api/index.js +++ b/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) diff --git a/test/unit/features/global-api/observable.spec.js b/test/unit/features/global-api/observable.spec.js new file mode 100644 index 00000000000..ecf2897d0a7 --- /dev/null +++ b/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) + }) +})