How to trigger a function using @click inside info

2019-08-30 01:56发布

问题:

My current code is

addpolygon: function(e) {
      var vm = this;
      var point = {
        lat: parseFloat(e.latLng.lat()),
        lng: parseFloat(e.latLng.lng())
      };
      vm.coord.push(point);
      vm.replot();
      vm.marker = new google.maps.Marker({
        position: point,
        map: vm.map,
        icon: "/fred.png"
      });
      vm.infowindow = new google.maps.InfoWindow({
        content:"<a class=\"btn btn-danger\" @click.native=\"removePoint("+vm.markerid+)\">Remove</a>",
        maxWidth: 300
      });
      vm.bindInfoWindow(vm.marker, vm.map, vm.infowindow);
      vm.markers[vm.markerid] = {
        marker: vm.marker,
        point: point
      };
      vm.markerid++;
    },

When I click on Remove, I need to trigger another function remove Point.

I defined it as

removePoint: function(id) {
      alert("adsf")
    },

But I am not able to trigger the same using the above code. Nothing happens when I click on the button remove. What is the problem regarding the same. Please help me to have a solution?

回答1:

New Solution

Call a global method from InfoWindow using plain-old click handler.

`onclick="removePoint(${vm.markerId})"`

Then use a closure to access your vm from the global method.

const vm = this window.removePoint = function(id) { vm.removePoint(id) }

IF you have multiple instances, you will need to extend this approach.

Old Solution

There are 2 issues here.

First, fix the syntax error concerning the quote.

vm.markerid + ")\">Remove</a>"

Even better, take advantage of template strings to avoid this kind of quote insanity.

vm.infowindow = new google.maps.InfoWindow({ content:`
<a class="btn btn-danger" @click.native="removePoint(${vm.markerid})">Remove</a>`, maxWidth: 300 });

Second, any function inside a vue template is always within the scope of the component. Assume a this. object is placed in front. So calling removePoint is really calling this.removePoint.

Define function inside instance.

vm.removePoint = function(id) { console.log(`removing point ${id}...`) }

Or make sure your component options defines removePoint in the methods section.

You can also define removePoint globally (on the window object) and call $window.removePoint(" + vm.markerId + ")" from the template if using a plugin such as https://www.npmjs.com/package/window-plugin.

@click.native=\"$window.removePoint(" + vm.markerid ...

function removePoint(id) { console.log(`removing point ${id}...`) }