引入多筆物件資料在Vue CLI
會有這篇文章是要記錄在寫sideProject的時候, 裡面有一段是要針對多筆物件資料存放在Vue的data中參考了老師的寫法, 大概歸納了一下
1 2 3 4 5 6 7 8 9 10 11
| var greenIcon = new L.Icon({ iconUrl: 'https://cdn.rawgit.com/pointhi/leaflet-color-markers/master/img/marker-icon-2x-green.png', shadowUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/images/marker-shadow.png', iconSize: [25, 41], iconAnchor: [12, 41], popupAnchor: [1, -34], shadowSize: [41, 41] });
L.marker([51.5, -0.09], {icon: greenIcon}).addTo(map);
|
要引入的資料, 有相同的config, 所以可以先把他包成物件, 再透過展開都放進去 (展開就是我要你的值, 不要你的結構)
所以外面的大括號就被去掉了
物件裡面的內容, 遵循 {key: value}
的形式, 這樣呼叫的時候就可以用obj.key
來呼叫
資料處理可以寫在export default
前
全部包成一個大物件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| let iconsConfig = { iconSize: [25, 41], iconAnchor: [12, 41], popupAnchor: [1, -34], shadowSize: [41, 41] };
let iconData = { green: new L.Icon({ iconUrl: "https://cdn.rawgit.com/pointhi/leaflet-color-markers/master/img/marker-icon-2x-green.png", ...iconsConfig }), grey: new L.Icon({ iconUrl: "https://cdn.rawgit.com/pointhi/leaflet-color-markers/master/img/marker-icon-2x-grey.png", ...iconsConfig }), red: new L.Icon({ iconUrl: "https://cdn.rawgit.com/pointhi/leaflet-color-markers/master/img/marker-icon-2x-red.png", ...iconsConfig }) };
export default { iconData }
|
引入外部資料
這也是看老師的code學習到的, 這邊是先在public
裡面新增一筆資料cityName.json
然後從github上把資料塞進去.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| [ { "CityName": "臺北市", "CityEngName": "Taipei City", "AreaList": [ { "ZipCode": "100", "AreaName": "中正區", "AreaEngName": "Zhongzheng Dist." }, { "ZipCode": "103", "AreaName": "大同區", "AreaEngName": "Datong Dist." },
|
我自己習慣是在mounted階段引入ajax的資料, 所以在mounted裡面寫上檔案名稱就可以了
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| export default{ data(){ return{ cityName:[] } } }
mounted() { this.initialMap() Promise.all([ this.axios.get('https://google.com.tw'), this.$http.get('cityName.json') ]).then(([res, cityNameRes]) => { this.cityName = cityNameRes.data }
|