Hannes A
Hannes A

Reputation: 97

How can I provide a function with composition API?

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

Answers (2)

Michal Levý
Michal Levý

Reputation: 37793

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

Upvotes: 1

Daniel
Daniel

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

Related Questions