I recently switched from React to Vue. In React, i often had a method in a child component, that would look something like this:
onClick = (e)=>{
const val = e.target.value;
this.props.onClick(val)
}
I see that Vue is very "free", and allows you to treat component methods and props as "the same thing".
Is there some way to distinguish between the two, like with this.props? What is the convention regarding this issue?
Props, data, computed properties and methods end up as properties on Vue instance - members may also include lifecycle hooks when a component is declared as a class. As with any other class, their names may collide.
In case there are members that are private (onClick method) and are parts of public API (onClick prop), they can be named differently, e.g. with underscore naming convention that is common in JS OOP:
...
props: {
onClick: Function
},
methods: {
_onClick() {...}
}
...
The use of naming conventions for private properties is suggested by Vue style guide.
In composition API and Vue 3, there is a clear distinction in setup because props object is available, so it could be done similarly to how the question suggests. There is no difference between props and instance properties in templates so the rest of the answer is still applicable.
You should take advantage of another Vue technique, instead of passing a function, using its event emitter system:
// MyComponent:
methods: {
onClick(e) {
const val = e.target.value;
this.emit('click', val);
}
}
...
<button @click="onClick">Click me</button>
//When you actually use your component
<MyComponent @click="() => { console.log('delegated onClick!'); }"/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With