You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Vue.js中通过CDN方式使用组件?

通过CDN使用Vue.js展示组件的实现方案

核心调整说明

通过CDN使用Vue时,浏览器无法直接识别.vue格式的单文件组件(SFC),因此需要先修改组件文件的结构,将模板内容转为JavaScript可识别的字符串形式。

1. 修改component.js

把原有的<template>标签内容迁移到组件选项的template字段中,改为模板字符串形式:

export default {
  template: `
    <div>
      Test
    </div>
  `,
  data: () => ({})
}

2. 调整index.html

在index.html中完成Vue CDN引入、组件导入、注册及使用:

<div id="app">
  <!-- 使用自定义组件 -->
  <my-test-component></my-test-component>
</div>

<!-- 引入Vue 3的CDN -->
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<!-- 引入组件文件,必须添加type="module"以支持ES模块语法 -->
<script type="module">
  // 导入自定义组件
  import MyTestComponent from './component.js'

  const { createApp } = Vue
  createApp({
    // 注册组件
    components: {
      MyTestComponent
    },
    data() {
      return {}
    }
  }).mount('#app')
</script>

兼容旧浏览器的备选方案

如果需要兼容不支持ES模块的旧浏览器,可将组件改为全局挂载形式:

  • 修改component.js:
window.MyTestComponent = {
  template: `
    <div>
      Test
    </div>
  `,
  data: () => ({})
}
  • 对应的index.html:
<div id="app">
  <my-test-component></my-test-component>
</div>

<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script src="./component.js"></script>
<script>
  const { createApp } = Vue
  createApp({
    components: {
      MyTestComponent: window.MyTestComponent
    },
    data() {
      return {}
    }
  }).mount('#app')
</script>

内容的提问来源于stack exchange,提问作者Svetlana Goodman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 02:10:36