Vuejs has become one of the most successfully applied, loved and trusted frontend JavaScript frameworks among our community. The Vue3 comes with a whole lot of new features. In this article we will go through all the fundamentals of Vue2 and Vue3. Basically a Vue Cheat Sheet to make your life easier.
We will break it down into different sections like global APIs, Vue Configs and the rest.
Vue DOM
-
new Vue({})
: This method provides the Vuejs instance an existing DOM element to mount on. This is where all your Vuejs Codes are defined -
el
: A CSS selector string or an actual HTMLElement that all the Vuejs codes will be mounted. -
template
: A string template which is used as the markup for the Vue instance.You Vuejs components are defined here. -
render: h => h(App)
: The render function receives a createElement method as it’s first argument used to create VNodes. Aliasing createElement to h is a common convention you’ll see in the Vue ecosystem and is actually required for JSX. If h is not available in the scope, your app will throw an error. -
renderError (createElement, err)
: This provides render output when the default render function encounters an error. The error encounter will be passed into the function as a second param.
Vue Data Property
-
props
: This is a list of attributes that are exposed to accept data from their parent component. You can implement this using an array and then pass all the parent data into it. It also accepts extra configs for data type checking and custom validation.
props:['users','samples']
-
data(){return{}}
: This is a data object for a particular Vuejs instance. Here Vuejs convert its properties into getter/setters to make it “reactive”.
data() {
return {
name:"Sunil",
age:80
}
}
-
computed
: Computed properties calculate a value rather than store a value. This computed properties are cached, and only re-computed on reactive dependency changes.
computed:{
sumNumbers:function() {
return this.a * 2
}
}
-
watch
:This is an object where keys are expressions to watch and values are the corresponding callbacks. Basically it listens to when your data property has been changed.
watch:{
name:function(val,oldVal) {
console.log('newval',val,'old',oldVal)
}
}
-
methods
: This are methods to be mixed into the Vue instance. This methods can be accessed directly on the VM instance using thethis
keyword. Always avoid using arrow functions to define methods.
methods:{
logName() {console.log(this.name)}
}
Sponsored:
Vue Lifecycle Hooks
A component in Vuejs has a lifecycle which is being managed by Vue itself when it creates the component, mounts the component to the DOM, updates the component and destroy the components.
-
beforeCreate
: This is called synchronously immediately after the instance has been initialized, before data observation and event/watcher setup.
beforeCreated(){console.log('Before Created')}
-
created
: This is called after the Vue instance is created.it is called synchronously immediately after the instance has been initialized, before data observation and event/watcher setup. -
beforeMount
: In this phase, it checks if any template is available in the object to be rendered in the DOM. If no template is found, then it considers the outer HTML of the defined element as a template. -
mounted
: This is called after the instance has been mounted, where el is replaced by the newly created vm.$el. If the root instance is mounted to an in-document element, vm.$el will also be in-document when mounted is called. If you want to wait untill all the veiw is rendered, you can use thenextTick
method inside the hook: this.$nextTick() -
beforeUpdate
: This gets fired before the changes reflecting the original DOM element.Also take note that hook is not called during server-side rendering. -
updated
:The component’s DOM will have been updated when this hook is called, so you can perform DOM-dependent operations here. However, in most cases you should avoid changing state inside the hook. To react to state changes, it’s usually better to use a computed property or watcher instead. -
beforeDestroy
:This is called before the Vue instance is destroyed. -
destroyed
: This is called after the Vue instance has been destroyed.
Vue 3 Lifecycle Hooks
Vue 3 also comes with its own life cycle hooks which is really great for development. To use them we will have to import them into our components like this:
import { onMounted, onUpdated, onUnmounted } from 'vue'
Here we get to only import the hooks that we want to use. Here are the Vue 3 life cycle hooks:
-
onBeforeMount
: This hook gets called before mounting occurs -
onMounted
: Once component is mounted this hook is called -
onBeforeUpdate
: Called once a reactive data changes and before its re-rendered. -
onUpdated
: This is called after re-rendering of the component. -
onBeforeUnmount
: This is called before the Vue instance is destroyed -
onUnmounted
: This is called immediately after the Vue Instance is destroyed. -
onActivated
: Components in Vuejs can be kept alive, this hook is called when this component is activated. -
onDeactivated
: This is called once akept-alive
component is deactivated. -
onErrorCaptured
: This is great for error handling. This hook is called once an error is captured in a child component.
Vue 3 Composition API
Before we can access the Vue3 composition API we have to first of all install it:
npm install @vue/composition-api
After the installation was successful we can now now import it into our main.js file:
import Vue from 'vue';
import CompositionApi from '@vue/composition-api';
Vue.use(CompositionApi);
With this done we are set to us the Vuejs Composition API in our application.
Now lets looking at some of the Vue 3 features:
-
**setup()**
: This function is called when an instance of a component has been created. This method takes in two parametersprops
andcontext
. - Props are reactive values and can be watched:
export default {
props: {
age: String,
},
setup(props) {
watch(() => {
console.log(`Sunil is : ` + props.age + "years old");
});
},
};
- Context here has this properties `attrs`, `slots`, `emit`, `parent`, `root`. Always remember that the `this` keyword is not available in the setup function meaning that this won’t work :
setup() {
function onClick() {
this.$emit // not available
}
}
-
refs
: The new way of getting reference to an element or component instance in a template is by using theref
method. To use this, we have to first of all import it into our application like this:
import { ref } from '@vue/composition-api'
And then use it like this in our component:
<template>
<div>{{ count }}</div>
</template>
<script>
import { ref } from '@vue/composition-api'
export default {
setup() {
return {
count: ref(0)
}
}
}
</script>
Vue Global Configs
The Vue.config
object is where we can define all our Vuejs global configs.
-
Vue.config.silent
: This config disables all Vuejs logs and warnings -
Vue.config.devtools
: This adds configuration whether to allow vue-devtools inspection or not -
Vue.config.performance
: This config enables component initalizing, compile, render and patch performance tracing in the browser devtool timeline. -
Vue.config.productionTip
: This enables production tip on Vue startup. -
Vue.config.ignoredElements
: Make Vue ignore custom elements defined outside of Vue (e.g., using the Web Components APIs). Otherwise, it will throw a warning about anUnknown custom element
. -
Vue.config.errorHandler
: This config assigns a handler for uncaught errors during component render function and watchers. -
Vue.config.optionMergeStrategies
: This defines custom merging strategies for options. This merge strategy receives the value of that option defined on the parent and child instances as the first and second arguments, respectively.
Vue Templates and Themes
As above cheat sheet helps you to speed up your workflow, there is another great thing called ready to use VueJs Templates, which are more than helpful, They help you create visually stunning applications using ready to use design components provided in the template package. You can definitely check them out for your application. You can download best free and premium VueJs Admin Dashboard and Website Templates at AdminMart and WrapPixel as well if you do not want to invest to start with.
Top comments (3)
Vue 3 is already released, some of the syntax is outdated
Yes Vue 3 is on cards, but we can not avoid Vue 2 for now, in future, sure people will shift to 3 only. Thanks
I wouldn't say they are outdated....some developers are still using Vue2