Adri HM
Adri HM

Reputation: 3050

Provide inject with setup function with Vue 3

Anybody knows how to provide a variable that is in the setup function?

export default {
  name: "MyComponent",
  provide: {
    myVariableThatIWantToProvide // This is not working
  },
  setup() {
    const myVariableThatIWantToProvide = ref('test');

    return {
      myVariableThatIWantToProvide
    };
  }
};
</script>

Upvotes: 5

Views: 4364

Answers (1)

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

You should import provide from vue and use inside the setup function :

import {ref,provide} from "vue"
export default {
  name: "MyComponent",
 
  setup() {
    const myVariableThatIWantToProvide = ref('test');
      provide ('myVariableThatIWantToProvide', myVariableThatIWantToProvide )
    return {
      myVariableThatIWantToProvide
    };
  }
};
</script>

in grandchild component :

import {inject} from "vue"
export default {
  name: "somechild",
 
  setup() {
      const myVariableThatIWantToProvide =inject ('myVariableThatIWantToProvide')
    return {
      myVariableThatIWantToProvide
    };
  }
};
</script>

Upvotes: 7

Related Questions