- 概述:目前ceisum集成到vue2主流有三种方式:
- 直接集成,需要修改webpack相关配置;
- 采用vue-cli-plugin-cesium集成,参考链接:vue-cli-plugin-cesium参考,无需额外配置,较为便捷;
- vue-cesium:项目地址:vue-cesium.开源项目,采取组件化引入的方式,建议新手不采用。
本文采用的是第一种方式。下面就开始吧~
- 第一步:搭建vue环境:
- 第二步:下载 cesium安装包
- 在vscode中打开终端,命令行:
npm install cesium -s
- main.js中全局引入:
Vue.config.productionTip = false var Cesium = require('cesium/Cesium'); var widgets= require('cesium/Widgets/widgets.css'); Vue.prototype.Cesium = Cesium Vue.prototype.widgets = widgets
完整代码:
import Vue from 'vue' import App from './App.vue' import router from './router' import store from './store' Vue.config.productionTip = false var Cesium = require('cesium/Cesium'); var widgets= require('cesium/Widgets/widgets.css'); Vue.prototype.Cesium = Cesium Vue.prototype.widgets = widgets new Vue({ router, store, render: h => h(App) }).$mount('#app')
- vue.config.js中修改如下:
const { defineConfig } = require("@vue/cli-service"); const CopyWebpackPlugin = require("copy-webpack-plugin"); const webpack = require("webpack"); const path = require("path"); const NodePolyfillPlugin = require('node-polyfill-webpack-plugin') let cesiumSource = './node_modules/cesium/Source' let cesiumWorkers = '../Build/Cesium/Workers' module.exports = defineConfig({ transpileDependencies: true, // 基本路径 publicPath: "./", // 输出文件目录 outputDir: "dist", // eslint-loader 是否在保存的时候检查 lintOnSave: false, // webpack-dev-server 相关配置 configureWebpack: { output: { sourcePrefix: " ", }, amd: { toUrlUndefined: true, }, resolve: { alias: { "@": path.resolve("src"), cesium: path.resolve(__dirname, cesiumSource), }, }, plugins: [ new CopyWebpackPlugin({ patterns: [ { from: path.join(cesiumSource, cesiumWorkers), to: "Workers" }, ], }), new CopyWebpackPlugin({ patterns: [{ from: path.join(cesiumSource, "Assets"), to: "Assets" }], }), new CopyWebpackPlugin({ patterns: [{ from: path.join(cesiumSource, "Widgets"), to: "Widgets" }], }), new CopyWebpackPlugin({ patterns: [ { from: path.join(cesiumSource, "ThirdParty/Workers"), to: "ThirdParty/Workers", }, ], }), new webpack.DefinePlugin({ CESIUM_BASE_URL: JSON.stringify("./"), }), new NodePolyfillPlugin(), ], }, });
- vue文件夹中新建CesiumView.vue:
<template> <div id="mycesium"></div> </template> <script> import * as Cesium from "../../node_modules/cesium"; export default { data() { return {}; }, created() {}, mounted() { new Cesium.Viewer("mycesium"); console.log(11); }, methods: {}, }; </script>
- 路由配置:
import Vue from 'vue' import VueRouter from 'vue-router' import CesiumView from "../views/CesiumView.vue"; Vue.use(VueRouter) const routes = [ { path: "/", component: CesiumView, }, ] const router = new VueRouter({ routes }) export default router
- 编译运行:
npm run serve
结果:
完结撒花~
- 在vscode中打开终端,命令行: