Using Props and Emitting Events in Vue.js 3 Composition API.

Posted by

Props and Emit Events in Vue.js Composition API

Props and Emit Events in Vue.js Composition API

In Vue.js version 3, the Composition API allows for more flexibility and organization compared to the Options API. One important concept in Vue.js is the passing of data between parent and child components using props and emitting events. Let’s take a look at how props and emit events work in Vue.js Composition API.

Props

Props are used to pass data from a parent component to a child component. In the Composition API, you can define props using the defineProps method. Here’s an example:

“`html

import { defineComponent, defineProps } from ‘vue’;

const ChildComponent = defineComponent({
setup(props) {
console.log(props.message);
}
});

export default {
components: {
ChildComponent
},
setup() {
const message = ‘Hello from Parent’;
return { message };
}
}

“`

In the example above, we define a prop called message in the parent component and pass it to the child component using the `:message` syntax. In the child component, we access the prop using the `props` argument in the `setup` function.

Emit Events

Emit events are used to communicate from a child component to a parent component. In the Composition API, you can define events using the defineEmits method. Here’s an example:

“`html

import { defineComponent, defineEmits } from ‘vue’;

const ChildComponent = defineComponent({
setup(_, { emit }) {
const handleClick = () => {
emit(‘button-clicked’);
}

return { handleClick };
}
});

export default {
components: {
ChildComponent
},
setup() {
return defineEmits([‘button-clicked’]);
}
}

“`

In the example above, we define an event called `button-clicked` in the parent component and listen for it using the `@` syntax in the template. In the child component, we emit the event using the `emit` function. The parent component can then handle the event using the corresponding method.

Overall, props and emit events are essential concepts in Vue.js for passing data between components. With the Composition API in Vue.js version 3, managing props and events is more organized and efficient.

0 0 votes
Article Rating
4 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@sohanrahman1897
6 months ago

Great

@valerypobelenskiy1001
6 months ago

Подскажите Антон как за деплоить проект на vue на гитхаб ?? и касательно Nuxt зачем сверх усложнять работу Vue если он и так прекрсно справляется со своими задачами??

@jahongirsalimov9587
6 months ago

И относительно материала, хотелось бы в будущем тоже узнать от вас про nuxt 3 , работодатели очень часто спрашивают, и про бэкенд в связке с nuxt3 и laravel

@jahongirsalimov9587
6 months ago

Еще чуток увеличьте экран, или может быть vscode растянете на весь экран . Смотреть можно, но недолго, глаза замылятся напрочь.