问题
在地图中有时候我们会遇上那种需要直接添加页面元素的操作内容。如:
我们给InfoWindow添加了一些页面内容使其在地图效果如下:
然后给按钮绑定了点击事件,如:
但是这样的点击确是无效的
然而我们确需要在本组件中自定义一个窗体内容并且给按钮绑定一个本组件能够访问事件。
解决方式
在vue中使用 vue.extend() 来生成html可以解决自定义元素添加事件的问题,并且可以访问本组件中的事件、数据或者进行路由跳转
备注:Vue.extend()和vue的组件很类似,其内容如:data(),methods,生命周期…等和组件是一样的。
代码:
<template>
<div class="login-box" id="login-box"></div>
</template>
<script>
import Vue from "vue";
export default {
data() {
return {
map: null,
infoWindow: null,
testOut: "这是外面的内容",
};
},
mounted() {
this.$map().then((AMap) => {
this.map = new AMap.Map("login-box", {
center: [117.00923, 36.675807],
zoom: 11,
});
this.infoWindow = new AMap.InfoWindow({
isCustom: true,
offset: new AMap.Pixel(16, -45),
});
// 提示:这里必须要保存一下this,在访问extend外部的内容时候需要:如 that.testOut
let that = this;
let InfoContent = Vue.extend({
template: `<div class="login-infowindow">
<h2>自定义标题</h2>
<button @click='clickA'>点击事件</button>
<button @click='clickB'>点击路由跳转</button>
</div>`,
data() {
return {
testIner: "这是里面的内容",
};
},
methods: {
clickA() {
console.log("123");
console.log(that.testOut);
console.log(this.testIner);
},
clickB() {
console.log("clickB");
that.$router.push("/home");
},
},
});
let component = new InfoContent().$mount();
this.infoWindow.setContent(component.$el);
this.infoWindow.open(this.map, [117.00923, 36.675807]);
});
},
};
</script>
<style lang="scss">
.login-box {
height: 100vh;
width: 100vw;
overflow: hidden;
.login-infowindow {
width: 200px;
height: 100px;
background: #fff;
}
}
</style>
效果:
只要能够通过that访问组件的外部内容必然就能访问$router这个对象,因此就可以进行跳转,否则请检查一下你的代码是否出现的一些阻塞的问题。