【问题标题】:Pass params in google maps API url in vue.js在 vue.js 中传递谷歌地图 API url 中的参数
【发布时间】:2020-11-30 15:03:17
【问题描述】:

我有两个从 $router.push() 获得的参数:{{ this.$route.params.lat }} 和{{ this.$route.params.lng }}。它们是纬度和经度坐标。

我必须在一个 URL 中传递他们两个来获取谷歌地图:

https://maps.googleapis.com/maps/api/staticmap?center={{ this.$route.params.lat }},{{ this.$route.params.lng }}&zoom=15&size=300x300&maptype=terrain&key=MY_API_KEY"
         

但是这样做不起作用,我有一个错误消息:

属性内的插值已被删除。请改用 v-bind 或冒号简写。例如,不要使用<div id="{{ val }}">,而是使用<div :id="val">

我该如何解决?

【问题讨论】:

  • 您尝试过错误信息中的建议吗?
  • 我试过但不知道怎么做。

标签: javascript vue.js


【解决方案1】:

如错误消息所示,您不能在 HTML 属性值中使用 {{ }} 模板语法。

解决这个问题的典型方法是使用v-bind syntax

<img :src="`https://maps.googleapis.com/maps/api/staticmap?center=${this.$route.params.lat},${this.$route.params.lng}&zoom=15&size=300x300&maptype=terrain&key=MY_API_KEY`">

为此,我将使用计算属性来生成 URL,以便您可以正确处理 URL 编码

computed: {
  mapUrl () {
    const url = "https://maps.googleapis.com/maps/api/staticmap"
    const params = new URLSearchParams({
      center: `${this.$route.params.lat},${this.$route.params.lng}`,
      zoom: 15,
      size: "300x300",
      maptype: "terrain",
      key: "MY_API_KEY"
    })
    return `${url}?${params}`
  }
}

然后你可以在你的模板中使用它

<img :src="mapUrl">

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-23
    • 2017-11-21
    • 1970-01-01
    • 2020-07-25
    • 2018-02-18
    • 1970-01-01
    • 2019-06-25
    相关资源
    最近更新 更多