Reputation: 97
Is it possible to provide a function in Vue 3 and then call the function in the child component?
I know that this worked with the option API
:
provide() {
return {
$list: this,
};
},
But how can I achieve the same with the composition API
?
Here is my approach:
Parent component:
setup(props) {
const handleEdit = (item) => {
emit("edit", item);
};
provide("$list", handleEdit);
return { handleEdit };
}
Child component:
setup(props) {
const { item } = props;
const list = inject("$list");
const handleEditItem = (e) => {
list.handleEdit(item);
};
}
And here the error
Uncaught TypeError: _ctx.handleEditItem is not a function
Upvotes: 1
Views: 2854
Reputation: 37793
setup(props) {
const { item } = props;
const list = inject("$list");
const handleEditItem = (e) => {
list(item);
};
return { handleEditItem }
}
this
)handleEdit
function so what you get when you call inject
is again just a functionhandleEditItem
from Child setup
- thats why you got error _ctx.handleEditItem is not a function
Upvotes: 1
Reputation: 35684
I think you can do it by passing an object, that way you can pass other variables and methods if needed.
parent.vue
setup(props) {
const handleEdit = (item) => {
emit("edit", item);
};
provide("$list", {handleEdit}); // <= change here
return { handleEdit };
}
Upvotes: 1