浏览代码

feat: support custom toString() in text interpolation and v-html (#8217)

close #8093
Mathieu TUDISCO 7 年之前
父节点
当前提交
0e4e45ec74
共有 3 个文件被更改,包括 13 次插入1 次删除
  1. 1 1
      src/shared/util.js
  2. 6 0
      test/unit/features/directives/html.spec.js
  3. 6 0
      test/unit/features/directives/text.spec.js

+ 1 - 1
src/shared/util.js

@@ -85,7 +85,7 @@ export function isPromise (val: any): boolean {
 export function toString (val: any): string {
   return val == null
     ? ''
-    : typeof val === 'object'
+    : Array.isArray(val) || (isPlainObject(val) && val.toString === _toString)
       ? JSON.stringify(val, null, 2)
       : String(val)
 }

+ 6 - 0
test/unit/features/directives/html.spec.js

@@ -44,6 +44,12 @@ describe('Directive v-html', () => {
       vm.a = {}
     }).then(() => {
       expect(vm.$el.innerHTML).toBe('{}')
+      vm.a = { toString () { return 'foo' } }
+    }).then(() => {
+      expect(vm.$el.innerHTML).toBe('foo')
+      vm.a = { toJSON () { return { foo: 'bar' } } }
+    }).then(() => {
+      expect(vm.$el.innerHTML).toBe('{\n  "foo": "bar"\n}')
       vm.a = 123
     }).then(() => {
       expect(vm.$el.innerHTML).toBe('123')

+ 6 - 0
test/unit/features/directives/text.spec.js

@@ -30,6 +30,12 @@ describe('Directive v-text', () => {
       vm.a = {}
     }).then(() => {
       expect(vm.$el.innerHTML).toBe('{}')
+      vm.a = { toString () { return 'foo' } }
+    }).then(() => {
+      expect(vm.$el.innerHTML).toBe('foo')
+      vm.a = { toJSON () { return { foo: 'bar' } } }
+    }).then(() => {
+      expect(vm.$el.innerHTML).toBe('{\n  "foo": "bar"\n}')
       vm.a = 123
     }).then(() => {
       expect(vm.$el.innerHTML).toBe('123')