vue3 简单封装GoogleMap组件

关于支持vue3的GoogleMap,暂时推荐两种
vue3-google-map
vue3 google maps
大家有较好的推荐欢迎交流
我这里选用的第二种

npm install -S @fawmi/vue-google-maps

然后再main中引入

// google-map
import VueGoogleMaps from '@fawmi/vue-google-maps'
app.use(VueGoogleMaps, {
  load: {
    key: 你的Google map key
    // language: 'de',
  }
})

新建一个xxx.vue的模块

 <div id="googleMap" class="mapCont">
        <GMapMap ref="mapRef" :center="center" :zoom="15">
          <GMapMarker v-for="(item, index) in markerOptions" :key="index" :position="item.position" />
        </GMapMap>
      </div>

GMapMap 为地图,GMapMarker为标记,其他需求看文档就好了

const center = reactive({ lat: 51.093048, lng: 6.84212 })
const mapKey = settings.googleMapKey
const markerOptions = reactive([
  {
    position: {
      lat: 51.093048,
      lng: 6.84212
    }
  }
])

设置地图中心和坐标点
在旁边随便加个搜索框,搜索并设为中心,搜索这里是使用的geocode

const reqSearch = () => {
  axios
    .get('https://maps.googleapis.com/maps/api/geocode/json?address=' + data.searchVal + '&key=' + mapKey)
    .then((res) => {
      console.log('res', res)
      if (res.data.status == 'OK') {
        center.lat = res.data.results[0].geometry.location.lat
        center.lng = res.data.results[0].geometry.location.lng
        markerOptions.splice(0, 1, { position: { lat: center.lat, lng: center.lng } })
        axios
          .get(`https://maps.googleapis.com/maps/api/geocode/json?&key=${mapKey}&latlng=${center.lat},${center.lng}`)
          .then((res) => {
            console.log(res)
            if (res.data.status == 'OK') {
              addressParse.lat = res.data.results[0].geometry.location.lat
              addressParse.lng = res.data.results[0].geometry.location.lng
              let sourceData = res.data.results.sort((a, b) => {
                return b.address_components.length - a.address_components.length
              })
              sourceData = sourceData[0].address_components
              addressParse.address = res.data.results[0].formatted_address
              sourceData.forEach((item) => {
                if (item.types[0] == 'country') {
                  addressParse.nation = item.long_name
                }
                if (item.types[0] == 'administrative_area_level_1') {
                  addressParse.Province = item.long_name
                }
                if (item.types[0] == 'administrative_area_level_2' || item.types[0] == 'locality') {
                  addressParse.city = item.long_name
                }
                if (item.types[0] == 'postal_code') {
                  addressParse.postal_code = item.long_name
                }
              })
              console.log(addressParse)
            } else {
              ElMessage.error('地址详情查询失败')
            }
          })
      } else {
        ElMessage.error('查询失败')
      }
    })
    .catch((err) => {
      console.log('err', err)
      ElMessage.error('查询失败')
    })
}

我这里首先通过地址搜索,得到经纬度,然后通过经纬度取货去更详细的地址信息,英语不好文档看的太折磨了,大家有什么好办法欢迎交流

这是我最终需要的一些值

const addressParse = reactive({
  nation: '',
  Province: '',
  city: '',
  address: '',
  postal_code: '',
  lat: '',
  lng: ''
})

在父组件使用

 <googleMap ref="searchAddRef" @getLocal="getLocal" style="height: 100%; width: 100%" />
import googleMap from '@c/googleMap/googleMap'

因为这里我用的是setup语法糖,需要来设置emit

const emit = defineEmits(['getLocal'])
emit('getLocal', addressParse)

父组件接收

const getLocal = (addressParse) => {
  console.log(addressParse)
}

完事(其实踩了好多坑)

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Vue3 的组件封装非常简单,下面是一个搜索组件封装示例: 首先,创建一个 Search.vue组件,它的模板如下: ```html <template> <div class="search"> <input type="text" v-model="searchInput" @input="handleInput" /> <button @click="handleSearch">搜索</button> </div> </template> ``` 在组件中,我们需要引入 `reactive`,这是 Vue3 中新加入的函数,用于将数据转换为响应式的数据。我们还需要定义 `props`,用于接收父组件传递的参数,以及定义 `emit`,用于向父组件发送事件。 ```javascript import { defineComponent, reactive, emit } from 'vue'; export default defineComponent({ name: 'Search', props: { placeholder: { type: String, default: '请输入关键词', }, }, setup(props, { emit }) { const searchInput = reactive({ value: '', }); const handleInput = (event) => { searchInput.value = event.target.value; }; const handleSearch = () => { emit('search', searchInput.value); }; return { searchInput, handleInput, handleSearch, }; }, }); ``` 在 `setup` 函数中,我们使用 `reactive` 将 `searchInput` 对象转换为响应式数据。当用户输入关键词时,`handleInput` 函数被调用,将输入的值赋值给 `searchInput.value`。当用户点击搜索按钮时,`handleSearch` 函数被调用,向父组件发送 `search` 事件,并将输入框的值作为参数传递给父组件。 最后,在父组件中使用该组件: ```html <template> <div> <Search placeholder="请输入关键词" @search="handleSearch" /> <ul> <li v-for="item in searchResult" :key="item.id">{{ item.name }}</li> </ul> </div> </template> <script> import Search from './Search.vue'; export default { components: { Search, }, data() { return { searchResult: [], }; }, methods: { handleSearch(keywords) { // 这里实现搜索逻辑,将搜索结果赋值给 searchResult this.searchResult = [ { id: 1, name: '搜索结果1' }, { id: 2, name: '搜索结果2' }, { id: 3, name: '搜索结果3' }, ]; }, }, }; </script> ``` 在父组件中,我们通过 `@search` 监听子组件的 `search` 事件,并在 `handleSearch` 方法中实现搜索逻辑。将搜索结果赋值给 `searchResult`,然后通过 `v-for` 渲染出结果列表。 这就是 Vue3 中搜索组件封装方法,简单易用。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值