scopeId.spec.ts 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. import { baseCompile } from '../src/compile'
  2. import { SET_SCOPE_ID } from '../src/runtimeHelpers'
  3. import { PatchFlags } from '@vue/shared'
  4. import { genFlagText } from './testUtils'
  5. /**
  6. * Ensure all slot functions are wrapped with _withCtx
  7. * which sets the currentRenderingInstance and currentScopeId when rendering
  8. * the slot.
  9. */
  10. describe('scopeId compiler support', () => {
  11. test('should only work in module mode', () => {
  12. expect(() => {
  13. baseCompile(``, { scopeId: 'test' })
  14. }).toThrow(`"scopeId" option is only supported in module mode`)
  15. })
  16. test('should wrap default slot', () => {
  17. const { code } = baseCompile(`<Child><div/></Child>`, {
  18. mode: 'module',
  19. scopeId: 'test'
  20. })
  21. expect(code).toMatch(`default: _withCtx(() => [`)
  22. expect(code).toMatchSnapshot()
  23. })
  24. test('should wrap named slots', () => {
  25. const { code } = baseCompile(
  26. `<Child>
  27. <template #foo="{ msg }">{{ msg }}</template>
  28. <template #bar><div/></template>
  29. </Child>
  30. `,
  31. {
  32. mode: 'module',
  33. scopeId: 'test'
  34. }
  35. )
  36. expect(code).toMatch(`foo: _withCtx(({ msg }) => [`)
  37. expect(code).toMatch(`bar: _withCtx(() => [`)
  38. expect(code).toMatchSnapshot()
  39. })
  40. test('should wrap dynamic slots', () => {
  41. const { code } = baseCompile(
  42. `<Child>
  43. <template #foo v-if="ok"><div/></template>
  44. <template v-for="i in list" #[i]><div/></template>
  45. </Child>
  46. `,
  47. {
  48. mode: 'module',
  49. scopeId: 'test'
  50. }
  51. )
  52. expect(code).toMatch(/name: "foo",\s+fn: _withCtx\(/)
  53. expect(code).toMatch(/name: i,\s+fn: _withCtx\(/)
  54. expect(code).toMatchSnapshot()
  55. })
  56. test('should push scopeId for hoisted nodes', () => {
  57. const { ast, code } = baseCompile(
  58. `<div><div>hello</div>{{ foo }}<div>world</div></div>`,
  59. {
  60. mode: 'module',
  61. scopeId: 'test',
  62. hoistStatic: true
  63. }
  64. )
  65. expect(ast.helpers).toContain(SET_SCOPE_ID)
  66. expect(ast.hoists.length).toBe(2)
  67. expect(code).toMatch(
  68. [
  69. `_setScopeId("test")`,
  70. `const _hoisted_1 = /*#__PURE__*/_createVNode("div", null, "hello", ${genFlagText(
  71. PatchFlags.HOISTED
  72. )})`,
  73. `const _hoisted_2 = /*#__PURE__*/_createVNode("div", null, "world", ${genFlagText(
  74. PatchFlags.HOISTED
  75. )})`,
  76. `_setScopeId(null)`
  77. ].join('\n')
  78. )
  79. expect(code).toMatchSnapshot()
  80. })
  81. })