二、快速上手vue3.0

185 阅读2分钟

一、创建一个 vue 应用

tips:已安装 18.3 或更高版本的 Node.js

创建的项目将使用基于 Vite 的构建设置,并允许我们使用 Vue 的单文件组件 (SFC)。

1、创建命令


npm create vue@latest


pnpm create vue@latest


yarn create vue@latest


bun create vue@latest

然后一路next...

2、安装依赖


cd <your-project-name>
npm install
npm run dev


cd <your-project-name>
pnpm install
pnpm run dev


cd <your-project-name>
yarn
yarn dev


cd <your-project-name>
bun install
bun run dev

生成的项目中的示例组件使用的是组合式 API 和 <script setup>,而非选项式 API。

3、打包应用

    
npm run build
    

    
pnpm run build
    


yarn build
    


bun run build
    

此命令会在 ./dist 文件夹中为你的应用创建一个生产环境的构建版本。

二、通过 CDN 使用 Vue

    
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    

通过 CDN 使用 Vue 时,不涉及“构建步骤”。这使得设置更加简单,并且可以用于增强静态的 HTML 或与后端框架集成。但是,你将无法使用单文件组件 (SFC) 语法。

1、使用全局构建版本

上面的链接使用了全局构建版本的 Vue,该版本的所有顶层 API 都以属性的形式暴露在了全局的 Vue 对象上。

代码示例:


<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>

<div id="app">{{ message }}</div>

<script>
  const { createApp, ref } = Vue

  createApp({
    setup() {
      const message = ref('Hello vue!')
      return {
        message
      }
    }
  }).mount('#app')
</script>

2、使用 ES 模块构建版本

现代浏览器大多都已原生支持 ES 模块。因此我们可以像这样通过 CDN 以及原生 ES 模块使用 Vue。


<div id="app">{{ message }}</div>

<script type="module">
  import { createApp, ref } from 'https://unpkg.com/vue@3/dist/vue.esm-browser.js'

  createApp({
    setup() {
      const message = ref('Hello Vue!')
      return {
        message
      }
    }
  }).mount('#app')
</script>

注意我们使用了 <script type="module">,且导入的 CDN URL 指向的是 Vue 的 ES 模块构建版本

3、启用 Import maps

在上面的示例中,我们使用了完整的 CDN URL 来导入,但在文档的其余部分中,你将看到如下代码:


import { createApp } from 'vue'

我们可以使用导入映射表 (Import Maps) 来告诉浏览器如何定位到导入的 vue:


<script type="importmap">
  {
    "imports": {
      "vue": "https://unpkg.com/vue@3/dist/vue.esm-browser.js"
    }
  }
</script>

<div id="app">{{ message }}</div>

<script type="module">
  import { createApp, ref } from 'vue'

  createApp({
    setup() {
      const message = ref('Hello Vue!')
      return {
        message
      }
    }
  }).mount('#app')
</script>

请注意,只有 Safari 16.4 以上版本支持。

4、拆分模块

随着对这份指南的逐步深入,我们可能需要将代码分割成单独的 JavaScript 文件,以便更容易管理。例如:


<!-- index.html -->
<div id="app"></div>

<script type="module">
  import { createApp } from 'vue'
  import MyComponent from './my-component.js'

  createApp(MyComponent).mount('#app')
</script>


// my-component.js
import { ref } from 'vue'
export default {
  setup() {
    const count = ref(0)
    return { count }
  },
  template: `<div>Count is: {{ count }}</div>`
}

由于安全原因,ES 模块只能通过 http:// 协议工作,也即是浏览器在打开网页时使用的协议。

(完)