Vue.js Components

Vue.js Component is an important feature of this framework. It is used to builds the custom elements. It can be reusable in the HTML file of the new Vue instance. We can also use the component to build custom elements within the root instance of Vue.

Since the Vue components are reused to the Vue instances, they accept the same options as the new Vue instances as data, computed, watch, methods, and life-cycle hooks. Only a few root-specific options, including el, are exceptions. If you want to create a component, use the following syntax:

Syntax:

Example: This example explains how we can use the Vue components in the Vue.js application.

Index.html

Main.js

Output: After the execution of this code, we will get the output, as shown below:

Vue.js Components

In the above example, we have seen the basic components with the basic options in the Vue.js application. But now, we are going to use the other options like data and methods with the Vue component. Although we have the data as a component function, we can use its properties in the same way as you do with the direct Vue instance. Also, we are going to add two methods, i.e., changename and the originalname. In changename, we change the name property, and in the originalname, we reset it back to the original name.

Here, we have also added the two events on the div tag, mouseover, and mouseout. The mouseover event calls the changename method, whereas the mouseout event calls the originalname method.

Now, we use the above example to understand this, and we will only do given changes in the .js file.

Example:

Main.js

Output: After executing this code, we will get the output, as shown below:

Vue.js Components

On the mouseover and mouseout event, the name of the first component is changed to James, and the second component remains the same. It is because the data function is a component, and it returns an object. Thus, when it is changed in one position, the same thing is not overwritten in other situations.

Vue.js Components

Dynamic Component

Dynamic components are build using the <component></component> element. Dynamic components can be bounded using a v-bind property. We can use the following syntax for the dynamic component.

Syntax:

Example: This example explains how we can use the dynamic component in the Vue.js component.

Index.html

Main.js

Output: After executing this code, we will get output, as shown below;

Vue.js Components

Pin It on Pinterest

Share This