---
title: "Vue + Vite"
description: "在纯 Vue + Vite 项目中经 @movk/mapbox/vite 与 vue-plugin 使用同一套组件。"
seo_title: "Vue + Vite"
seo_description: "Use @movk/mapbox/vite to auto-import components and composables, and @movk/mapbox/vue-plugin to inject tokens, with usage identical to Nuxt."
canonical_url: "https://mapbox.mhaibaraai.cn/docs/getting-started/vue"
---
# Vue + Vite

> 在纯 Vue + Vite 项目中经 @movk/mapbox/vite 与 vue-plugin 使用同一套组件。

## Vite 插件

在 `vite.config.ts` 中加入插件，负责组件与 composables 的自动导入：

```ts [vite.config.ts]
import vue from '@vitejs/plugin-vue'
import Mapbox from '@movk/mapbox/vite'

export default defineConfig({
  plugins: [vue(), Mapbox()]
})
```

`Mapbox()` 内部自动注册组件解析器与自动导入项，独立 Vue + Vite 项目直接使用即可。

## 复用已有 unplugin 实例

部分库（如 `@nuxt/ui`）的 Vite 插件内置了唯一的 `unplugin-vue-components` / `unplugin-auto-import` 实例。这时无需再加 `Mapbox()`，改用 `@movk/mapbox/unplugin` 导出的 `mapboxComponentResolver` 与 `mapboxAutoImports`，注入宿主插件复用：

```ts [vite.config.ts]
import vue from '@vitejs/plugin-vue'
import ui from '@nuxt/ui/vite'
import { mapboxAutoImports, mapboxComponentResolver } from '@movk/mapbox/unplugin'

export default defineConfig({
  plugins: [
    vue(),
    ui({
      components: { resolvers: [mapboxComponentResolver()] },
      autoImport: { imports: [...mapboxAutoImports()] }
    })
  ]
})
```

> \[\!NOTE\]
> 
> @nuxt/ui
> 
>  检测到第二个 
> 
> unplugin-vue-components
> 
>  / 
> 
> unplugin-auto-import
> 
>  实例会直接抛错，因此与其同用时务必走注入复用方式，而非再叠加 
> 
> Mapbox()
> 
> 。

`mapboxComponentResolver` 默认以 `Mapbox` 为组件前缀，可通过 `mapboxComponentResolver({ prefix: 'Mb' })` 自定义。

## 注册 Vue 插件

在入口注册 `vue-plugin`，传入 token 并引入运行时样式：

```ts [main.ts]
import { createApp } from 'vue'
import MapboxPlugin from '@movk/mapbox/vue-plugin'
import '@movk/mapbox/index.css'
import App from './App.vue'

createApp(App)
  .use(MapboxPlugin, {
    accessToken: import.meta.env.VITE_MAPBOX_TOKEN,
    tiandituToken: import.meta.env.VITE_TIANDITU_TOKEN
  })
  .mount('#app')
```

配套 `.env`：

```bash [.env]
VITE_MAPBOX_TOKEN=pk.your_mapbox_access_token
VITE_TIANDITU_TOKEN=your_tianditu_tk
```

> \[\!NOTE\]
> 
> tiandituToken
> 
>  是浏览器端类型 key（Referer 校验），仅用于天地图底图瓦片。天地图检索/地理编码/行政区划/路线等 Web 服务是服务端专用接口（IP 白名单校验），不能通过 
> 
> vue-plugin
> 
>  注入，也不能放进 
> 
> VITE\_
> 
>  前缀的环境变量（会被打进客户端 bundle）；需要在自建的服务端（Nuxt Nitro、Vite dev 中间件等）里用 
> 
> createTianditu
> 
>  调用，详见 
> 
> 天地图 Web 服务
> 
> 。

## 用法一致

组件与 composables 由 `@movk/mapbox/vite` 自动导入，用法与 Nuxt 完全一致：

```vue [App.vue]
<script setup lang="ts">
const center = ref<[number, number]>([116.397, 39.908])
</script>

<template>
  <div style="height: 480px">
    <MapboxMap v-model:center="center" :options="{ style: 'mapbox://styles/mapbox/streets-v12', zoom: 9 }">
      <MapboxNavigationControl position="top-right" />
    </MapboxMap>
  </div>
</template>
```


## Sitemap

See the full [sitemap](/sitemap.md) for all pages.
