vue router 的 router-link in google maps infowindow

vue router's router-link in google maps infowindow

我的这个工作正常,除了我想使用 <router-link> 标签而不是 <a> 标签,因为 <a> 标签不同于 <router-link> (拦截点击事件并且不重新加载页面)重新加载页面。

const contentString = `
    <div class="popup">
        <a href="/places/${place._id}">
            <img src="..." />
            <h5>${place.name}</h5>
            <p>${place.gmap.address}</p>
        </a>
    </div>`

const infoWindow = new google.maps.InfoWindow()
infoWindow.setContent(contentString)

如果我用 <router-link> 替换 <a> 标签,它不会像 <router-link> 在 vuejs 模板中那样渲染到 <a> 标签。

你是对的。 router-link 没有渲染,因为 Vue.js 没有机会渲染它。你可以先让 vue.js 渲染你的模板,使用 innerHTML 获取渲染结果作为字符串,然后将字符串传递给 Google Maps API(setContent ).

我想在这里提供2个解决方案。

  1. 第一个很容易阅读和理解。把它当作一个普通的组件使用,但是在标签中添加 v-show="false" 这样它就不会出现在你的视图中。 (place 可以作为 prop 传递)

    <div id="app">
      <api v-show="false" :place="place"></api>
    </div>
    

    Vue 实例:

    new Vue({
      router: new VueRouter({}),
      el: '#app',
      data: {
        place: {
          id: 1,
          name: 'awesome-name',
          address: 'somewhere',
        }
      },
      components: {
        api: {
          props: [ 'place' ],
          template: `
            <div class="api">
            <div class="popup">
              <router-link :to="'/places/' + place.id">
                <h5>{{place.name}}</h5>
                <p>{{place.address}}</p>          
              </router-link>
            </div>
            </div>
          `,
        },
      },
      mounted() {
        console.log(this.$children[0].$el.innerHTML);
        //=> <div class="popup"><a href="#/places/1" class=""><h5>awesome-name</h5> <p>somewhere</p></a></div>
      },
    });
    
  2. 如果你不想污染你的 html,你可以使用 Vue.extend 以编程方式生成组件的 vm,创建一个虚拟 dom,然后将您的虚拟机安装到已创建的 dom.

    const myComp = Vue.extend({
      router: this.$options.router,
      template: `
        <div class="api">
        <div class="popup">
          <router-link to="/places/${this.place.id}">
            <h5>${this.place.name}</h5>
            <p>${this.place.address}</p>          
          </router-link>
        </div>
        </div>
      `,
    });
    const comp = new myComp().$mount(document.createElement('div'));
    console.log(comp.$el.innerHTML);
    //=> <div class="popup"><a href="#/places/1" class=""><h5>awesome-name</h5> <p>somewhere</p></a></div>
    

我把上面的解决方案合并成一个fiddle,请看一下。