将展示组件示例的代码封装成一个组件,以便重复使用

    1. <template>
    2. <div class="demo">
    3. <h2>{{component.__sourceCodeTitle}}</h2>
    4. <div class="demo-component">
    5. <component :is="component" />
    6. </div>
    7. <div class="demo-actions">
    8. <Button @click="toggle">查看代码</Button>
    9. </div>
    10. <div class="demo-code" v-if="codeVisible">
    11. <pre class="language-html" v-html="html"></pre>
    12. </div>
    13. </div>
    14. </template>
    15. <script lang="ts">
    16. import Button from '../lib/Button.vue'
    17. import 'prismjs'
    18. import 'prismjs/themes/prism-okaidia.css'
    19. import { computed, ref } from 'vue'
    20. const Prism = (window as any).Prism
    21. export default {
    22. props: {
    23. component: {
    24. type: Object
    25. }
    26. },
    27. setup(props){
    28. const codeVisible = ref(false)
    29. const html = computed(()=>{
    30. return Prism.highlight(props.component.__sourceCode,Prism.languages.html, 'html')
    31. })
    32. const toggle = () => {
    33. codeVisible.value = !codeVisible.value
    34. }
    35. return {
    36. Prism,
    37. html,
    38. codeVisible,
    39. toggle
    40. }
    41. },
    42. components: {
    43. Button
    44. }
    45. }
    46. </script>

    重复使用

    1. <template>
    2. <h1>Switch 组件示例</h1>
    3. <Demo :component="Switch1Demo" />
    4. <Demo :component="Switch2Demo" />
    5. </template>