I am trying to pass a reactive object using vues provide and inject and I get the [Vue warn]: injection "settings" not found.
warning and when I log out settings it returns as undefined.
What am I doing wrong here?
I made a quick little CodeSandbox to replicate the issue.
If anyone has any ideas why this is happening please let me know!
Cheers!
Test.vue
<script>
import { defineComponent, provide, reactive } from "vue";
export default defineComponent({
setup() {
const settings = reactive({
theme: "light",
color: "#F092AD",
id: 69,
});
provide("settings", settings);
return {};
},
});
</script>
App.vue
<template>
<pre>{{ settings }}</pre>
</template>
<script>
import { defineComponent, inject } from "vue";
export default defineComponent({
setup() {
const settings = inject("settings");
console.log(`settings → `, settings);
return { settings };
},
});
</script>
CodePudding user response:
You can only use provide function to provide data to a component's descendants.
In your case component is not descendant so you get warning because nothing is provided.
You can ether use app level provide like:
app.provide(/* key */ 'message', /* value */ 'hello!')
or some global state management tool like pinia or vuex.
Take a look at codesandbox or snippet:
const { reactive, provide, inject } = Vue
const app = Vue.createApp({
setup() {
const msg = inject("message");
const settings = reactive({
theme: "light",
color: "#F092AD",
id: 69,
});
provide("settings", settings);
return { msg };
},
})
app.component('child', {
template: `<pre><test /></pre>`,
})
app.component('test', {
template: `<pre>{{ settings }}</pre>`,
setup() {
const settings = inject("settings");
return { settings };
},
})
app.provide(/* key */ "message", /* value */ "hello!");
app.mount('#demo')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
<pre>{{ msg }}</pre>
<child />
</div>