2024-07-17 xxx.vue?raw作用 ==> 把xxx.vue轉換成原始碼,以字串形式返回

叶乘风發表於2024-07-17

常見ui庫會有個程式碼預覽,這是怎麼做到的?就是透過匯入一個vue檔案的原始碼,用pre和code包裹著顯示的,比如:

<template>
  <div>
    <transition name="slide-fade">
      <pre v-highlight>
        <code class="language-js">
            {{ sourceCode }}                      
        </code>
       </pre>
    </transition>
  </div>
</template>

<script setup>
import { onMounted, ref } from "vue";
const props = defineProps({
  compName: {
    type: String,
    default: "button",
    required: true,
  },
  demoName: {
    type: String,
    default: "demo1",
    required: true,
  },
});
const sourceCode = ref("");

const getSourceCode = async () => {
  sourceCode.value = (
    await import(`@packages/${props.compName}/doc/${props.demoName}.vue?raw`)
  ).default;
  console.log("sourceCode.value", sourceCode);
};

onMounted(() => {
  console.log("props", props);
  getSourceCode();
});
</script>

<style lang="less" scoped>
code {
  padding: 0;
  white-space: pre-wrap;
}
</style>

看見這行程式碼的raw沒有:await import(`@packages/${props.compName}/doc/${props.demoName}.vue?raw`)

如果不寫這個,嘿!您猜怎麼著。

相關文章