2

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

0

2 Answers 2

2

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 };
}
Sign up to request clarification or add additional context in comments.

Comments

1
setup(props) {
    const { item } = props;
    const list = inject("$list");
        
    const handleEditItem = (e) => {
        list(item);
    };

    return { handleEditItem } 
}
  1. in your Vue 2 example, you are providing whole component (this)
  2. In Vue 3 code, you are providing just the handleEdit function so what you get when you call inject is again just a function
  3. You forget to return handleEditItem from Child setup - thats why you got error _ctx.handleEditItem is not a function

4 Comments

Thank you! But that also not worked. Do you now how to provide the whole component with the composition API? Because this is no longer available.
You just can't provide whole component using Composition API. And I dont think it is a good idea anyway
This would work too. Maybe he meant to return list as the handler rather than recreating handleEditItem in the child. (Assuming that's what he's trying to do. It's unclear.)
The code is from OP ....I was trying to make just minimal changes required to make it work. And fail to notice the OP forget to return handleEditItem from setup. Fixed now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.