瀏覽代碼

should fallback on default slot if no content is left (#1965)

Evan You 10 年之前
父節點
當前提交
9edb3582b1
共有 2 個文件被更改,包括 17 次插入5 次删除
  1. 6 5
      src/directives/element/slot.js
  2. 11 0
      test/unit/specs/directives/element/slot_spec.js

+ 6 - 5
src/directives/element/slot.js

@@ -35,11 +35,12 @@ export default {
       // Default content
       var self = this
       var compileDefaultContent = function () {
-        self.compile(
-          extractFragment(raw.childNodes, raw, true),
-          context,
-          host
-        )
+        var content = extractFragment(raw.childNodes, raw, true)
+        if (content.hasChildNodes()) {
+          self.compile(content, context, host)
+        } else {
+          self.fallback()
+        }
       }
       if (!host._isCompiled) {
         // defer until the end of instance compilation,

+ 11 - 0
test/unit/specs/directives/element/slot_spec.js

@@ -59,6 +59,17 @@ describe('Slot Distribution', function () {
     expect(el.lastChild.textContent).toBe('slot b')
   })
 
+  it('fallback content with mixed named/unnamed slots', function () {
+    el.innerHTML = '<p slot="b">slot b</p>'
+    options.template =
+      '<slot><p>fallback a</p></slot>' +
+      '<slot name="b">fallback b</slot>'
+    mount()
+    expect(el.childNodes.length).toBe(2)
+    expect(el.firstChild.textContent).toBe('fallback a')
+    expect(el.lastChild.textContent).toBe('slot b')
+  })
+
   it('selector matching multiple elements', function () {
     el.innerHTML = '<p slot="t">1</p><div></div><p slot="t">2</p>'
     options.template = '<slot name="t"></slot>'