johnsoncodehk/vite-plugin-vue-component-preview

How can I use template in preview slot?

ALiangLiang opened this issue · 3 comments

How can I preview component with slot? I cannot put template in the preview slot. It resulted in the error below.

Error: Codegen node is missing for element/if/for node. Apply appropriate transforms first.

<template>
  <div>
    <slot />
  </div>
</template>

<preview lang="md">
  <script setup>
  const msgs= ['1', '2']
  </script>
  <template v-for="msg in msgs">
    <slot>
      <template>
        test {{ msg }}
      </template>
    </slot>
  </template>
</preview>

Although the error is not raised in my case, the <slot /> does not seem to work.
This is because the content will be ignored if the component for <slot> is given, maybe :)
However, I found a way to preview the component in such a situation.
Importing the component itself in the <script setup> section can resolve the issue as follows:

<template>
    <div>
        <slot></slot>
    </div>
</template>

<preview lang="md">
  <script setup>
    import TestPreview from './TestPreview.vue'
    const msgs= ['1', '2']
  </script>

  <template v-for="msg in msgs">
    <TestPreview>
        test {{ msg }}
    </TestPreview>
  </template>

</preview>

Note TestPreview.vue is the file name you consider.

Although the error is not raised in my case, the <slot /> does not seem to work. This is because the content will be ignored if the component for <slot> is given, maybe :) However, I found a way to preview the component in such a situation. Importing the component itself in the <script setup> section can resolve the issue as follows:

<template>
    <div>
        <slot></slot>
    </div>
</template>

<preview lang="md">
  <script setup>
    import TestPreview from './TestPreview.vue'
    const msgs= ['1', '2']
  </script>

  <template v-for="msg in msgs">
    <TestPreview>
        test {{ msg }}
    </TestPreview>
  </template>

</preview>

Note TestPreview.vue is the file name you consider.

Thanks. It works. slot cannot use v-model and inside <template>. So importing self component is the best solution. Hopefully documentation should mention it so developer can known about this solution.

<template>
  <div>
    <slot />
  </div>
</template>

<preview lang="md">
  <script setup>
  const msgs= ['1', '2']
  </script>
  <template v-for="msg in msgs">
    <slot>
      <template>
        test {{ msg }}
      </template>
    </slot>
  </template>
</preview>

test {{ msg }} in this code is actually fallback content, so it will not be passed on.

https://vuejs.org/guide/components/slots.html#fallback-content