10 Tips & Tricks To Make You A Better VueJS Developer
10 Tips & Tricks To Make You A Better VueJS Developer
<template>
...
<my-table>
<template #row="{ item }">
/* some content here. You can freely use 'item' here */
</template>
</my-table>
...
</template>
The $on(‘hook:’)
This is a nice feature you can use if you want to define a custom event
listener or third party plugin in the created or mounted hook and
need to remove it in the beforeDestroy hook to not cause any memory
leaks. With the $on(‘hook:’) method you can use defining/removing
the event in just one lifecycle method instead of two.
mounted() {
const aThirdPartyPlugin = aThirdPartyPlugin()
this.$on('hook:beforeDestroy', () => {
aThirdPartyPlugin.destroy()
})
}
Prop Validation
You probably already know that you can validate your props to be
primitives like String, Number or even Object. But you can also make
use custom validators, for example if you want to validate against a
List of Strings:
alertType: {
validator: value => ['signup', 'login', 'logout'].includes(value)
}
<template>
...
<aButton @[someEvent]="handleSomeEvent()"/>
...
</template>
<script>
...
data(){
return{
...
someEvent: someCondition ? "click" : "dblclick"
}
},
methods:{
handleSomeEvent(){
// handle some event
}
}
...
</script>
And whats also really neat --> you can apply the same pattern to
dynamic HTML attributes, props and much more!
<template>
<router-view :key="$route.fullPath"></router-view>
</template>
instead of:
<template>
<childComponent :prop1="prop1"
:prop2="prop2"
:prop3="prop3"
:prop4="prop4"
...
/>
</template>
<template>
<div>
...
<childComponent v-on="$listeners"/>
...
</div>
</template>
In case the child component is at the root of its parent it will get those
by default and you do not need this little trick.
$createElement
Each Vue-Instance has by default access to the $createElement
method to create and return virtual nodes. This can be utilized for
example to use markup in methods that can be passed via the v-html
directive. In functional components this method can be accessed as
the first parameter in the render function.
Using JSX
Since Vue CLI 3 it supports the use of JSX by default so that you can
now write your code in JSX if you like to (and maybe come from
React) which comes in handy for example for writing functional
components. If you are not on Vue CLI 3 yet you can make use of
babel-plugin-transform-vue-jsx to have JSX-support!
export default: {
model: {
event: 'change',
prop: 'checked'
}
}
Conclusion
I hope I could give you some tips for you to help you become a better
VueJs Developer. If you are also into react Development you should
check out my post 10 Tips & Tricks that will make you a better ReactJS
Dev. Feel free to leave a comment and follow me for more upcoming
posts!