I really enjoy using Vue.js, and every time I use a framework, I like to delve into its capabilities and features. Through this article, I’ve introduced you to ten cool tips and tricks that you may not have realized could help you become a better Vue developer.
Better slot syntax
With the release of Vue 2.6, a shorthand for slots has been introduced that can be used for events (for example, @click for v-on:click events) or for colons for bindings (: SRC). For example, if you have a table component, you can use this function as follows:
<template> ... <my-table> <template #row={item}> /* something that you can use with "item" */ </template> </my-table>... </template>
$on(‘ hook: ‘) can help you simplify your code
Removing event listeners is a common best practice because it helps avoid memory leaks and prevents event collisions.
This is a good feature if you want to define a custom event listener or third-party plug-in in a created or mounted hook and need to remove it in the beforeDestroy hook to avoid causing any memory leaks. Here is a typical setup:
mounted () {
window.addEventListener('resize', this.resizeHandler);
},
beforeDestroy () {
window.removeEventListener('resize', this.resizeHandler);
}
With the $on(‘hook:’) method, you can define/delete events using only one lifecycle method instead of two.
mounted () { window.addEventListener('resize', this.resizeHandler); this.$on("hook:beforeDestroy", () => { window.removeEventListener('resize', this.resizeHandler); })}
$on can also listen for the lifecycle hooks of child components
Finally, the fact that the lifecycle hooks emit custom events means that the parent component can listen to the lifecycle hooks of its children.
It listens for events in normal mode (@event) and can be handled like any other custom event.
<child-comp @hook:mounted="someFunction" />
Use immediate: true to trigger watcher on initialization
Vue Watchers is a good way to add advanced functionality (for example, API calls) that runs when observations change.
By default, observers are not run at initialization time. Depending on your functionality, this may mean that some data is not fully initialized.
watch: {
title: (newTitle, oldTitle) => {
console.log("Title changed from " + oldTitle + " to " + newTitle)
}
}
If you want wather to run immediately after the instance is initialized, all you have to do is convert wather to an object with handler(newVal, oldVal) and immediate immediate immediate: true.
watch: {
title: {
immediate: true,
handler(newTitle, oldTitle) {
console.log("Title changed from " + oldTitle + " to " + newTitle)
}
}
}
You should always validate your Prop
Verifying Props is one of the basic methods in Vue.
You probably already know that you can validate props as primitive types, such as strings, numbers, or even objects. You can also use a custom validator — for example, if you want to validate a list of strings:
props: { status: { type: String, required: true, validator: function (value) { return [ 'syncing', 'synced', 'version-conflict', 'error' ].indexOf(value) ! == -1}}}
Dynamic instruction parameter
One of the coolest features of Vue 2.6 is the ability to dynamically pass instruction parameters to components. Suppose you have a button component, and you want to listen for click events in some cases and double-click events in other cases. This is where these instructions come in handy:
<template>
...
<aButton @[someEvent]="handleSomeEvent()" />...
</template>
<script>
...
data(){
return{
...
someEvent: someCondition ? "click" : "dbclick"
}
},
methods: {
handleSomeEvent(){
// handle some event
}
}
</script>
Also, this is actually pretty neat – you can apply the same pattern to dynamic HTML properties, props, etc.
Reuse components on the same route
Developers often encounter situations where multiple routes resolve into the same VUE component. The problem is that Vue, for performance reasons, by default shared components will not be re-rendered, and if you try to switch between routes using the same component, nothing changes.
const routes = [
{
path: "/a",
component: MyComponent
},
{
path: "/b",
component: MyComponent
},
];
If you still want to re-render these components, you can do so by providing the :key property in the Router – View component.
<template>
<router-view :key="$route.path"></router-view>
</template>
Passing all Props to child components is easy
This is a cool feature that lets you pass all props from the parent to the child. This will be especially handy if you have another component wrapped in the component. So, instead of giving props one by one, you can use this to give props one by one:
<template>
<childComponent v-bind="$props" />
</template>
Instead of:
<template>
<childComponent :prop1="prop1" :prop2="prop2" :prop="prop3" :prop4="prop4" ... />
</template>
Passing all event listening to child components is easy
If the child component is not in the root directory of the parent component, all event listeners can be passed from the parent to the child, as shown below:
<template>
<div>
...
<childComponentv-on="$listeners" />...
<div>
</template>
If the child component is at the root of its parent, it gets the components by default, so you don’t need to use this little trick.
$createElement
By default, each Vue instance has access to the $createElement method to create and return virtual nodes. For example, you can use it to use tags in methods that can be passed through V-HTML directives. In the function component, this method can be accessed as the first parameter in the render function.
Use the JSX
Since Vue CLI 3 supports JSX by default, you can now (if you wish) write code in JSX (for example, easily write function components). If you are not already using Vue CLI 3, you can get JSX support using babel-plugin-transform-vue-jSX.
Custom v – model
By default, the v-model is the syntactic sugar on the @Input event listener and the :value attribute. However, you can specify a model property in your Vue component to define what event and value properties to use — great!
export default: {
model: {
event: 'change',
prop: 'checked'
}
}
conclusion
This is by no means a complete list of VUEJS tips, these are just some of the ones I personally found most useful, and some of them took me a long time to practice in Vue, so I thought I could share them with you.
I hope they are as helpful to you as I am!
What are your favorite VUEJS tips and tricks? I also want to learn from you!
Reference link:
- Medium.com/better-prog…
- Learnvue. Co / 2020/01/7 – s…
Now focus onFront-end Full Stack DeveloperWeChat public number, also send some network high-quality video course network disk data, can save a lot of money for you!