I’m trying to provide
a value from an mixin
that needs to get fetched first.
It seems that the provide
is synchronous because the provided key is an empty observer at the time the children is created. I dont know how to make sure the children has the config data at its creation time.
Note I’m using Vue 2.7
I’ve already researched quite a bit but i haven’t found a solution or a question with a similar problem.
- Vue docs
( i also tried it with computed() as injected value but that changes nothing )
Here is an basic example:
App.vue
<script>
import { configMixin } from '@/mixins/configMixin'
import Child from './Child.vue'
export default {
mixins: ['configMixin'],
components: [Child],
async created() {
await this.initConfig()
},
provide() {
config: this.config
}
}
</script>
<template>
<div>
<Child />
</div>
</template>
configMixin.js
import { fetchMixin } from '@/mixins/fetchMixin';
export const configMixin = {
mixins: [fetchMixin],
data() {
return {
config: {},
unwatchConfig: null
};
},
beforeDestroy() {
// Clean up the watcher when the component is destroyed
if (this.unwatchConfig) {
this.unwatchConfig(); // This un-watches the watcher
}
},
methods: {
async initConfig() {
try {
this.config = await this.fetch('api/config');
} catch (error) {
console.error('Failed to fetch config:', error);
} finally {
this.setupConfigWatcher(); // Setup the watcher after fetching
}
},
setupConfigWatcher() {
this.unwatchConfig = this.$watch(
'config',
(newValue) => {
this.saveConfig();
},
{ deep: true }
);
},
async saveConfig() {
try {
await this.fetch('api/config', {
method: 'POST',
body: this.config
});
} catch (error) {
console.error('Failed to save config:', error);
}
}
}
};
Child.vue
<script>
export default {
inject: ['config'],
created() {
console.log(this.config)
this.config.message = 'Hello World'
}
}
</script>
<template>
<div>
Child
</div>
</template>