Passing data and functions from Components in Vue js 3

Passing data and functions from Components in Vue js 3

14-Sep-2024
| |
Image Carousel

Hello developers in this tutorial we will discuss about how to create components and pass data and functions

Table of Contents

S.no Contents-topics
1 What are components
2 Setup new Vue js project
3 Create new components(parent and child)
4 Router file
5 Run the Code

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 

Tags: Vue.js 3, Create components, Vue components, Single File Components (SFC), Component structure, Component options, Component , pass data in vue js , pass functions from components in vue js 3 , pass data and functions from components in vue js 3,Front-end development , vue js tutorial , vue js 3 , vue js 3 tutorial ,,
0 Comments (Please let us know your query)
Leave Comment
Leave Comment
Articles from other Categories
Load More

Newsletter