Guys sorry if is dump question am learing VUE3 and befeore i post this question i research google and not found result.
I want to define global property in Root Component that will be used in all child properties. Property like BASE_URL link or TITLE.
Here is my Root Component
<script>
import HeaderTop from './pages/partials/header_top.vue'
import HeaderMiddle from './pages/partials/header_middle.vue'
import MainNavbar from './pages/partials/main_navbar.vue'
import MainFooter from './pages/partials/footer.vue'
export default {
data() {
return {
show: true,
baseURL: 'www.example.com'
}
},
mounted() {
this.show = true;
},
components: {
HeaderTop,
HeaderMiddle,
MainNavbar,
MainFooter
}
}
</script>
<template>...</template>
HeaderMiddle.vue component
Here i want to call property from RootComponent
<script>
import app from '../../RootComponent.vue';
export default {
// i also try this ant this not work
data() {
return {
baseURL: app.baseURL
}
}
}
</script>
<template>
<div >
<div >
<div >
<div >
<a href="/" title="">
<h1>{{baseURL}}</h1> <!-- not work -->
<h1>{{app.baseURL}}</h1> <!-- not work -->
<h1>{{app.baseURL}}</h1> <!-- not work -->
</a>
</div>
</div>
</div>
</div>
</template>
App.js
require('./bootstrap');
import { createApp } from 'vue';
import router from './router'
import RootComponent from './RootComponent.vue'
const app = createApp(RootComponent);
app.use(router).mount("#app");
CodePudding user response:
It's recommended to provide baseUrl
as global property :
require('./bootstrap');
import { createApp } from 'vue';
import router from './router'
import RootComponent from './RootComponent.vue'
const app = createApp(RootComponent);
app.config.globalProperties.baseUrl='www.example.com'
app.use(router).mount("#app");
and use it inside any child component like :
<script>
export default {
data() {
return {
baseURL: this.baseURL
}
}
}
</script>
<template>
<div >
<div >
<div >
<div >
<a href="/" title="">
<h1>{{baseURL}}</h1>
</a>
</div>
</div>
</div>
</div>
</template>
CodePudding user response:
Usually, when we need to pass data from the parent to a child component, we use props. However, imagine the case where we have a large component tree, and a deeply nested component needs something from a distant ancestor component. With only props, we would have to pass the same prop across the entire parent chain. But we can use Props drilling to deepchild.
Props drilling with provide
and inject
.
**PROVIDE**
- A parent component can serve as a dependency provider for all its descendants
Example Provide:
export default {
provide: {
message: 'hello!'
}
}
Example Inject:
export default {
inject: ['message'],
created() {
console.log(this.message) // injected value
}
}
You can check more details from here