Discussion icon indicating copy to clipboard operation
Discussion copied to clipboard

call vue.js function in javascript on change event

Open ThomasRalee opened this issue 9 years ago • 3 comments

Hi Guys,

I am wondering if it's possible to trigger a vue function in my change event

$(document.body).on('change', 'select[name^="dropdown"]', function () {
    this.functionName();
});

I am returned with this error Uncaught TypeError: this.functionName is not a function

Am i missing something?

Thanks in advance!

ThomasRalee avatar Jul 13 '15 18:07 ThomasRalee

Are you trying to put this into ready hook or something? Your issue is with this inside callback does not point to the vue instance. Here is what you could try:

var vm = this;
$(document.body).on('change', 'select[name^="dropdown"]', function () {
    vm.functionName();
});

simplesmiler avatar Jul 13 '15 18:07 simplesmiler

This would probably also work:

$(document.body).on('change', 'select[name^="dropdown"]', function () {
    this.functionName();
}.bind(this));

But most likely, this is not the right thing to use here. Just give your vue app a name, like:

var vue = new Vue({
    el: '#app'
});

and you can access vue globally. If you're using components, you might have to write something like

vue.$children[0].functionName()

Just use the Chrome inspector or Vue plugin for Chrome if you wanna explore the properties that are available.

swift1 avatar Jul 19 '15 04:07 swift1

i have the same issue i add this code in my created () {}

created() {
			Event.$on('login', function(){
				this.a()
			})
	}

despite function a is in my methods block

Zedonboy avatar Apr 03 '17 05:04 Zedonboy