Просмотр исходного кода

fix(sfc): treat custom block content as raw text

Evan You 6 лет назад
Родитель
Сommit
d6275a3c31

+ 5 - 1
packages/compiler-core/src/options.ts

@@ -10,7 +10,11 @@ export interface ParserOptions {
   isCustomElement?: (tag: string) => boolean
   isBuiltInComponent?: (tag: string) => symbol | void
   getNamespace?: (tag: string, parent: ElementNode | undefined) => Namespace
-  getTextMode?: (tag: string, ns: Namespace) => TextModes
+  getTextMode?: (
+    tag: string,
+    ns: Namespace,
+    parent: ElementNode | undefined
+  ) => TextModes
   delimiters?: [string, string] // ['{{', '}}']
 
   // Map to HTML entities. E.g., `{ "amp;": "&" }`

+ 1 - 1
packages/compiler-core/src/parse.ts

@@ -365,7 +365,7 @@ function parseElement(
 
   // Children.
   ancestors.push(element)
-  const mode = context.options.getTextMode(element.tag, element.ns)
+  const mode = context.options.getTextMode(element.tag, element.ns, parent)
   const children = parseChildren(context, mode, ancestors)
   ancestors.pop()
 

+ 8 - 2
packages/compiler-sfc/__tests__/parse.spec.ts

@@ -78,8 +78,8 @@ h1 { color: red }
     <template v-if="ok">ok</template>
     <div><div></div></div>
     `
-    const sfc = parse(`<template>${content}</template>`).descriptor
-    expect(sfc.template!.content).toBe(content)
+    const { descriptor } = parse(`<template>${content}</template>`)
+    expect(descriptor.template!.content).toBe(content)
   })
 
   test('error tolerance', () => {
@@ -102,6 +102,12 @@ h1 { color: red }
     expect(errors.length).toBe(1)
   })
 
+  test('treat custom blocks as raw text', () => {
+    const { errors, descriptor } = parse(`<foo> <-& </foo>`)
+    expect(errors.length).toBe(0)
+    expect(descriptor.customBlocks[0].content).toBe(` <-& `)
+  })
+
   describe('warnings', () => {
     test('should only allow single template element', () => {
       parse(`<template><div/></template><template><div/></template>`)

+ 11 - 1
packages/compiler-sfc/src/parse.ts

@@ -2,7 +2,8 @@ import {
   NodeTypes,
   ElementNode,
   SourceLocation,
-  CompilerError
+  CompilerError,
+  TextModes
 } from '@vue/compiler-core'
 import { RawSourceMap, SourceMapGenerator } from 'source-map'
 import LRUCache from 'lru-cache'
@@ -89,6 +90,15 @@ export function parse(
     isNativeTag: () => true,
     // preserve all whitespaces
     isPreTag: () => true,
+    getTextMode: (tag, _ns, parent) => {
+      // all top level elements except <template> are parsed as raw text
+      // containers
+      if (!parent && tag !== 'template') {
+        return TextModes.RAWTEXT
+      } else {
+        return TextModes.DATA
+      }
+    },
     onError: e => {
       errors.push(e)
     }