Reputation: 1485
I'm using arrow functions to run multiple events on @click like below:
<btn @click="()=> {variable = "5";
myFunction(variable);
myFunction2('something');
$emit('argument', myFunction3())}"
>Run functions!</btn>
I want to know if this is secure/good practice?
If not, why? Can I ask for any arguments?
Upvotes: 4
Views: 5880
Reputation: 135792
tl;dr In general, arrow functions work in event handlers (doesn't mean that you should use them, see below).
But, first, your example code int the question wouldn't work:
new Vue({
el: '#app',
methods: {
myFunction() {},
myFunction2() {},
myFunction3() {},
}
})
<script src="https://unpkg.com/vue"></script>
<script src="https://unpkg.com/vuex"></script>
<div id="app">
<p>
<button @click="()=> {variable = "5"; myFunction(variable); myFunction2('something'); $emit('argument', myFunction3())}"
>Run functions!</button>
</p>
</div>
As you can see, the problem is the "
in "5"
closes the attribute.
Second: If you fix the "
(see below) the code doesn't work the way you think seem to think it does. When using variable
that way:
@click="()=> {variable = "5"; myFunction(variable); myFunction2('something'); $emit('argument', myFunction3())}"
it is not a local variable to that scope. It is expected to be a property in the component (e.g. a data
or computed property).
To use locally, you would have to properly declare it, using var
, let
or const
:
new Vue({
el: '#app',
data: {},
methods: {
myFunction(a) { console.log("myFunction", a) },
myFunction2(a) { console.log("myFunction2", a) },
myFunction3() { console.log("myFunction3") },
}
})
<script src="https://unpkg.com/vue"></script>
<script src="https://unpkg.com/vuex"></script>
<div id="app">
<p>
<button @click="()=> {let variable = '5'; myFunction(variable); myFunction2('something'); $emit('argument', myFunction3())}"
>Run functions!</button>
</p>
</div>
Final and most important point. That practice leads to code that is way harder to maintain.
It's an unnecessary way of having logic in the template. The standard way of doing this is simply creating a method and calling it from the template.
Demo:
new Vue({
el: '#app',
data: {},
methods: {
myMethod() {
let variable = '5';
this.myFunction(variable);
this.myFunction2('something');
this.$emit('argument', myFunction3())
},
myFunction(a) { console.log("myFunction", a) },
myFunction2(a) { console.log("myFunction2", a) },
myFunction3() { console.log("myFunction3") },
}
})
<script src="https://unpkg.com/vue"></script>
<script src="https://unpkg.com/vuex"></script>
<div id="app">
<p>
<button @click="myMethod">Run functions!</button>
</p>
</div>
Upvotes: 5