简体   繁体   中英

Vue.js 3 call anonymous function inside event handler

Is it possible to call an anonymous function inside the event handler on Vue.js 3?

I found these options across the internet:

<button @click="return function() { console.log('test')}()">Click me</button>

<button @click="() => { console.log('test') }">Click me</button> //ES6

<button @click="(function(){ console.log('Test'); })();">Click me</button>

None of them seems to be working. Maybe they used to work with Vue.js 2 but I can't confirm that.

The issue is that console is not defined in the template, so you should define it as property in your data, or call a method that use the console :

<button @click="() => { logDatat('some data log') }">Click me</button> 

<button @click="() => { myConsole.log }">Click me</button> 

....

data(){
  return {
     myConsole : console
   }
}

The three syntaxes are valid as shown in this demo:

DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM