sparkle
sparkle

Reputation: 7400

Vue 3 Instante Root Component with data after Promise

I need to initialize a Vue 3 app with data (item object) returned from a Promise and access it from all components. The fetched item should be passed to the app before anything else.

import { createApp } from 'vue';
import store from "../store";
import DetailPage from '../views/DetailPage.vue'

my_promise().then(fetched_item => {
  const app =  createApp(DetailPage)
  app.item = fetched_item // this doesn't works
  const vm = app.use(store).mount('#app')
})
 

detailpage.vue

<template>
  <navbar-component></navbar-component>
</template>

<script>
import NavBar from '@/components/detailpage/NavBar.vue'
export default {
  name: 'DetailPage',
  data(){
    return {
      item: {text: 'default'}
    }
  },
  components: {
    'navbar-component': NavBar
  }
}
</script>

but if I try to access this.$root.item from another nested components

mounted(){
  console.log("root", this.$root.item)
}

I get

Proxy {text: "default"}  

instead of the fetched item passed at initialization

Upvotes: 0

Views: 1307

Answers (1)

tony19
tony19

Reputation: 138316

createApp() returns the application instance, but you need the root component (i.e., the result of app.mount()), which allows accessing the component's data properties:

const app = createApp(DetailPage)
const vm = app.use(store).mount('#app')
vm.item = fetched_item

Upvotes: 1

Related Questions