VueJS: Passing data from root element to child components through router-view - javascript

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

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 :).

Related

How to get data of a state in one step above

I am a beginner and I am learning React JS. I am making a demo project. I need a help there.
In my app.js there is routes shop.js and review.js. The data and states is in shop.js. Now how can I pass some states data on review.js from shop.js?
Image
How can I do that?
It's recommended to lift the shared state up to their closest common ancestor (app.js).
please check
https://reactjs.org/docs/lifting-state-up.html
You could use Context
Context provides a way to pass data through the component tree without having to pass props down manually at every level.
In a typical React application, data is passed top-down (parent to child) via props, but such usage can be cumbersome for certain types of props (e.g. locale preference, UI theme) that are required by many components within an application. Context provides a way to share values like these between components without having to explicitly pass a prop through every level of the tree.

Understanding the props concept in React

While I'm learning React, it's always said that you should keep your state in the parent component and pass them as props to its children.
But in the real world, whenever I start building a react app, I end up passing data from a child component to its parent.
For example, if I have to implement a form somewhere in my react app, I create an extra component for it (for example, FormComponent) and import it in my App component.
But now, I have to pass the form data form the FormComponent to the App component. In other words, from the child component (FormComponent) to the parent (App component).
And this was just an example. Usually, I always end up in situations where I have to pass data from child to parent rather than the other way around.
Do I misunderstand the concept of passing props completely?
If we stay with the above example, is my approach, right?
You can't pass data from child to parent as in React, The Data Flows Down.
So usually you pass callbacks from parent to its children, but the state remains in the parent.
This is commonly called a “top-down” or “unidirectional” data flow. Any state is always owned by some specific component, and any data or UI derived from that state can only affect components “below” them in the tree.
If you in a situation where the code becomes unreadable, unmaintainable, you should consider Lifting the State Up.
Often, several components need to reflect the same changing data. We recommend lifting the shared state up to their closest common ancestor.
Aside from it, a common anti-pattern is Prop Drilling, Context API, and many state libraries like Redux, MobX, and Recoil trying to solve such problems with some extra features.
1- In your case you can pass a function ( Example: handleSubmit() ) through props from parent to child.
And so when this function is called the child's data would be hundled from the parent.
you can use this doc page to inspire your code.
2- Otherwise you can use react redux, and then you can hundle all data at any component in your project using one global state called redux store.
want to learn more about react redux click here.
3- Have a nice day ^_^ .

Correct way to have a global variable in react

I'm developing a react.js project and before the main component is rendered, I call a function that returns an object that all components should be able to access. What is the correct way of doing this in react? Currently, I'm just passing it as a prop to the main component and then I suppose I should have to remember to pass it as a prop to all other components. Is there an easier or better way of doing this?
It seems like you are doing something like Redux. Passing the object as props should be okay. You could make a higher-order component that wraps your components and adds access to that global object via props. This is similar to Redux's connect.
As the expectation in React is application-wide concerns ,like a flux/redux/apollo store, are kept in a root provider component’s context and then accessed elsewhere in the component tree via a Higher Order Component or render props. This provides relief from globals and circular dependencies, and makes testing those components easier.
However, if you have non-component code that will need access to configuration values, you may need to use config global and writing components in a way that accepts config values from props.
see: https://github.com/lorenwest/node-config

Access the prop of the root component in VueJS

In my page, I have a set of components and subcomponents like that:
<TournamentTabs :tournament="{{ json_encode($tournament) }}">
<TournamentTab>
<TournamentTabGeneral></TournamentTabGeneral>
<TournamentTabVenue></TournamentTabVenue>
etc.
</TournamentTab>
</TournamentTabs>
Right now, I use Laravel for getting $tournament value.
Now, I would like prop tournament to be available to all TournamentTabs children, but when accessing this.tournament, I get undefined
How should I access tournament value in all chidlren???
There are many ways to do it.
Firstly, the TournamentTabs is not a root component as I can see. Root component - it's the component where Vue instance mounts (in most cases div#app) that can be accessible via this.$root anywhere.
You can access it via this.$parent.tournament, but this is not a best way to do it, because you will end up like this.$parent.$parent.$parent....tournament if you need to access property from deeply nested components.
You can try vuex library to implement the central application storage.

Flux: How to make Stores for a Variable Number of React Components?

In the flux tutorial, it says that "Application state is maintained only in the stores."
Short version: I have a variable number of components in my app, each of which maintains state. How am I supposed to use stores here? It seems like I need one store per component.
Long version:
I wanted to create a tree of text elements with a variable number of nodes (essentially an app that just lets me create an arbitrary tree and visualize it in HTML).
My current architecture has a Tree element in React, maintains the state:
{ children: [], // children are trees.
parent: someParent }
However, given that each subtree in my tree has state, it appears that I will need one store per subtree! What is the correct way to architect this code?
No, keep the state in just 1 component. All the other components should get their data in the form of props.
In addition, the component that keeps the state shouldn't be aware of the state, but you should be using a store to keep it. Generally, these types of components that know about the state, are named "Container Components". Those components that don't know about state and receive their data with props are called "Presentational Components" (or "dumb components"). Read more here: http://redux.js.org/docs/basics/UsageWithReact.html
Use Redux architecture
Keep your state global,
use container components and reducers to pass props to your components.
http://redux.js.org/docs/api/bindActionCreators.html

Categories

Resources