Hello developers in this tutorial we will discuss about how to create components and pass data and functions
Table of Contents
1:What are Components
Components are piece of code that we can reuse means we can call components in any parent component or its child component
2:Setup new Vue js project
For setting up new vue js project pls consider link given below
3:Create new components(parent and child)
Create a parent component view file src/views/Parent.vue
code for Parent.vue : Copy
<template>
<ChildComponent :childname="parentname" :clickFunction="alertFunction"/>
</template>
<script>
import ChildComponent from '../components/child.vue'
export default{
name:'Parent',
components:{
ChildComponent
},
data()
{
return{
parentname:"Code with Vineet Maanas"
}
},
methods:
{
alertFunction()
{
alert("THis is alert");
}
}
}
</script>
Create a child component src/components/Child.vue
code for Child.vue : Copy
<template>
<h1>Welcome to {{ childname }}</h1>
<button v-on:click="clickFunction">Click Here</button>
</template>
<script>
export default{
name:'ChildComponent',
props:{
childname:String,
clickFunction:Function
}
}
</script>
4:Router File
If your project don't have default router file consider below post for how to create custom route file in vue js
code for route.js :Copy
import { createRouter, createWebHistory } from 'vue-router'
import App from '../App.vue'
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{
path: '/',
name: 'App',
component: App
},
]
})
export default router
5:Run the project
To check and run the project simply hit npm run dev on the cmd
0 Comments (Please let us know your query)