背景
Vue3.0想把有些公共的變量及方法放到一個單獨的js文件中,免得每個組件都要聲明一次。
環境
Vue3.0
@arcgis/core 4.24.7
解決方案
方法一,只針對全局變量:
main.js
1 const app = createApp(App) 2 app.config.globalProperties.$gisServerAddr = 'http://192.168.1.127:6080/arcgis/rest/services/' 3 app.use(store).use(router).use(ElementPlus).mount('#app')
.vue文件引用
1 import {getCurrentInstance } from 'vue' 2 const { 3 appContext: { 4 config: { globalProperties } 5 } 6 } = getCurrentInstance() 7 const queryUrl = 8 globalProperties.$gisServerAddr + 'wjwf/patch_2000/FeatureServer/0' //取到全局變量
方法二,全局變量和全局方法都可用(推薦):
①全局變量
在src/assets文件夾下新建utils/gisUrl.js
gisUrl.js
1 // 測試環境 2 const serviceUrl = { 3 wj2000Url: 'http://192.168.1.127:6080/arcgis/rest/services/wjwf/wjwf2000new/MapServer/tile/{level}/{row}/{col}?blankTile=false', 4 patchesLayerUrl: 'http://192.168.1.127:6080/arcgis/rest/services/wjwf/patch_2000/FeatureServer/0', 5 } 6 7 export default serviceUrl
.vue文件引用即可
1 import serviceUrl from '@/assets/utils/gisUrls'
②方法跟變量類似,但是方法一般會有很多,所以export的方式就不用export default的方式了:
在src/assets文件夾下新建utils/publicModules.js
// 公共的數據和方法 import Search from '@arcgis/core/widgets/Search' const addSearchWidget = (view, layer, baseInfos, zoom) => { const searchWidget = new Search({ view: view, container: 'searchWidget', includeDefaultSources: false, sources: [ { layer: layer, name: '網格', placeholder: '輸入網格編號', outFields: ['*'], searchFields: ['wgid'], suggestionTemplate: '網格編號:{wgid}', locationEnabled: false, displayField: 'wgid', exactMatch: false, maxResults: 6, minSuggestCharacters: 0, maxSuggestions: 10, resultGraphicEnabled: true, suggestionsEnabled: true // zoomScale: 1 } ] }) searchWidget.on('select-result', function (event) { view.goTo({ target: event.result.feature, zoom: zoom }) }) // Add the search widget to the top right corner of the view view.ui.add(searchWidget, { position: 'manual' }) } export { addSearchWidget }
.vue文件調用
1 import { addSearchWidget }f rom '@/assets/utils/publicModules'
參考網址