Reputation: 7623
Generally, when I have a variable that several child components should be able to access, I store them in the data object of my root Vue element and subsequently pass them down to child components through properties.
However, I've recently progressed to using vue-router and my root vue element only contains a "router-view" component, which controls what child component is being served to the user.
Below is what my root element looks like (I am using vue-cli):
<template>
<div id="app">
<router-view></router-view>
</div>
</template>
<script>
export default {
name: 'app'
}
</script>
<style lang="scss">
</style>
As a result, the approach of passing variables to child components through properties, which I used prior to using vue router, doesn't seem viable anymore.
How should I be passing data from my root Vue element to my child components through vue router? Should I even be using this approach to achieve my goal of accessing "global" variables?
I've read several threads that reference using Vuex for state management and while I'm unopposed to learning and using it - it feels a little overkill for what I'm trying to achieve at this stage.
EDIT (clarifying question)
Several of my child components make API calls to a local / production server (depending on the node environment) and I find myself copying the “if-else” logic multiple times to determine which server the component should be making the API call to. So I thought it would be a much better approach of declaring a “server” variable at the root element and then pass it down to the child elements that need to make API calls
Upvotes: 3
Views: 1960
Reputation:
Vuex is a great tool, however, if you're trying to pass some basic data - such as a record id - to a child component, you should be looking at route props.
https://router.vuejs.org/en/essentials/passing-props.html
With route route props, you declare props in your child components in the normal fashion. However, the must be named the same are the route property.
// child component
props: ['id']
// route definition
{ path: '/item/:id', component: Item, props: true },
As you can see the :id
is then passed to the child component id
prop.
As your application grows in it's complexity, vuex (or a state manager of your choosing) would be a much more appropriate tool to use. When you become comfortable with it and learn some of the really nice tricks, you'll see what you've been missing :).
Upvotes: 2