techferment
Published in

techferment

6. Vue Components

In Vue.js, Vue Components is one of the important features that create custom elements, which can be reused in HTML.

Vue Single Components consist of 3 parts:

  1. script tag: for defining JavaScript Code and inside script tag there we’ll be a Vue instance where you can define data, methods…
  2. style tag: for defining CSS design part

Creation of a Component in Vue

For creating a component in the Vue project, create a .vue file in the components folder and provide it the name of your choice.

Now, in this newly created .vue file, you can write HTML, Javascript, and CSS in the <template>, <script>, and <style> tags respectively.

// hello.vue Component
<template>
<h1 class="title">Vue.js Component | {{msg}}</h1>
</template>

<script>
export default {
name: 'HelloComponent',
data: ()=>({
msg: "Hello"
}),
methods:{
}
}
</script>

<style>
.title{ color: red }
</style>

Importing of a component in Vue

The import syntax for importing a component in any other component of Vue is pretty simple and easy; you just have to import the component inside the script tag using the ES6 syntax as shown in the code snippet below:

// app.vue, Importing hello.vue component<template>
<div>
<h1>App Component</h1>
</div>
</template>

<script>
import Hello from @/components/hello.vue
export default {
name: 'app',
data: ()=>({
}),
methods:{
}
}
</script>

After importing the component successfully, all you need to do is to create an object with the name of components and provide the name in the components object as shown below:

// app.vue, Importing hello.vue component<template>
<div>
<h1>App Component</h1>
</div>
</template>

<script>
import Hello from @/components/hello.vue
export default {
name: 'app',
components:{
Hello
},
data: ()=>({
}),
methods:{
}
}
</script>

Now, you can use it anywhere inside the <template> tag of the component. For example, if we want to import it into the App.vue, the syntax would be like this:

// app.vue, Importing hello.vue component<template>
<div>
<h1>App Component</h1>
<Hello/>
</div>
</template>

<script>
import Hello from @/components/hello.vue
export default {
name: 'app',
components:{
Hello
},
data: ()=>({
}),
methods:{
}
}
</script>

After completing all this setup, save each and every file that you have changed and go back to the browser. and This is how you can use Vue Components.

Keep watching this and follow us for more tech articles or you can reach out to me for any doubt and suggestions and the next blog in the series will be published soon.

Thanks

Happy Coding!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Vrijraj Singh

Google Developer Expert for Web Technologies & Firebase | Developer Advocate | GDG Organizer for GDG Jalandhar