Vue/Vuex - How to retrieve data from grandchildren - javascript

started with VueJs for the first time
yesterday and now I'm stuck..
I have a parent component who has child items that also has a child inside them (I call them grandchildren). I want to fetch data from all the grandchildren when i click a button in the parent but i can't figure out how.
In my mind a want to call an event from parent to to all the grandchildrens that they should store their data to vuex store. Is this possible somehow or is there another way to do this?
// Data
blocks = [
{
id: 1,
type: 'HeadingBlock',
title: 'Hello',
color: 'blue'
},
{
id: 2,
type: 'ImageBlock',
image_id: 2
}
];
// App.js
<ContentBlocks :blocks="blocks" / >
// ContentBlock.vue
<ContentBlockItem v-for="(block, index) in blocks" :component="block.type" ... />
// ContentBlockItem.vue
<component :is="component" :block="block" /> // Grandchild
// component aka the grandchild (eg. HeadingBlock.vue)
data() {
return {
title: 'Hello - I want save the changed data for this heading',
color: 'blue'
}
}
So, the only call to action happens in the parent by a "save"-button. And i want as little logic in grandchildren as possible (to make it easy to create new ones, like a "ParagraphBlock").
Thx in advance

It is possible to emit() a global Event that all your components subscribe to - however it seems rather impractical. (e.g. this.$root.emit('saveData') in parent; in all children to listen to it: this.$root.on('saveData'))
A more practical approach is to store all your component data in the store in the first place. And have each component retrieve its state from the store. (e.g. in a computed property: title() { return this.$store.myComponent.title }.
The trick here is obviously to set all your store-data correctly (e.g. with componentIDs to match it correctly). To do this you need to be aware, that vuex does not support maps or sets. Also, you have to set each property/element individually - you cannot set nested structures in one go bu thave to do it recursively. Hereby Arrays have to be filled with native array methods (push(), splice()) and Object properties have to be set with Vue.set(object, key, value).

For accessing data between parent and child component you can use one of the best features of vue is vuex store. It's really helpful when you want to pass data to child component and update that data in child and again pass back to parent without the use of props and event emit.
Here is a link you can follow for your web application
https://medium.com/dailyjs/mastering-vuex-zero-to-hero-e0ca1f421d45
https://medium.com/vue-mastery/vuex-explained-visually-f17c8c76d6c4
I hope this will help you.

Related

Vuex/Redux store pattern - sharing single source of data in parent and child components that require variations of that data

I understand the benefits of using a store pattern and having a single source of truth for data shared across components in an application, and making API calls in a store action that gets called by components rather than making separate requests in every component that requires the data.
It's my understanding that if this data needs to change in some way, depending on the component using the data, this data can be updated by calling a store action with the appropriate filters/args, and updating the global store var accordingly.
However, I am struggling to understand how to solve the issue whereby a parent component requires one version of this data, and a child of that component requires another.
Consider the following example:
In an API, there exists a GET method on an endpoint to return all people. A flag can be passed to return people who are off sick:
GET: api/people returns ['John Smith', 'Joe Bloggs', 'Jane Doe']
GET: api/people?isOffSick=true returns ['Jane Doe']
A parent component in the front end application requires the unfiltered data, but a child component requires the filtered data. For arguments sake, the API does not return the isOffSick boolean in the response, so 2 separate requests need to be made.
Consider the following example in Vue.js:
// store.js
export const store = createStore({
state: {
people: []
},
actions: {
fetchPeople(filters) {
// ...
const res = api.get('/people' + queryString);
commit('setPeople', res.data);
}
},
mutations: {
setPeople(state, people) {
state.people = people;
}
}
});
// parent.vue - requires ALL people (NO filters/args passed to API)
export default {
mounted() {
this.setPeople();
},
computed: {
...mapState([
'people'
])
},
methods: {
...mapActions(['setPeople']),
}
}
// child.vue - requires only people who are off sick (filters/args passed to API)
export default {
mounted() {
this.setPeople({ isOffSick: true });
},
computed: {
...mapState([
'people'
])
},
methods: {
...mapActions(['setPeople']),
}
}
The parent component sets the store var with the data it requires, and then the child overwrites that store var with the data it requires.
Obviously the shared store var is not compatible with both components.
What is the preferred solution to this problem for a store pattern? Storing separate state inside the child component seems to violate the single source of truth for the data, which is partly the reason for using a store pattern in the first place.
Edit:
My question is pertaining to the architecture of the store pattern, rather than asking for a solution to this specific example. I appreciate that the API response in this example does not provide enough information to filter the global store of people, i.e. using a getter, for use in the child component.
What I am asking is: where is an appropriate place to store this second set of people if I wanted to stay true to a store focused design pattern?
It seems wrong somehow to create another store variable to hold the data just for the child component, yet it also seems counter-intuitive to store the second set of data in the child component's state, as that would not be in line with a store pattern approach and keeping components "dumb".
If there were numerous places that required variations on the people data that could only be created by a separate API call, there would either be a) lots of store variables for each "variation" of the data, or b) separate API calls and state in each of these components.
Thanks to tao I've found what I'm looking for:
The best approach would be to return the isOffSick property in the API response, then filtering the single list of people (e.g. using a store getter), thus having a single source of truth for all people in the store and preventing the need for another API request.
If that was not possible, it would make sense to add a secondary store variable for isOffSick people, to be consumed by the child component.

How to create isolated Vuex states for every initialized instance of a component in Vue?

I'm new to Vue.
I see people suggest that we need to use a Vuex module for components to store their state data so we can access that data in the parent component.
For example, I have MarkdownEditor.vue component and I'll need to access its data from the parent. I store the state in a Vuex module, e.g markdownEditorStore.js... I can access this state in the parent component easily, like, this.$store.state.markdownEditor.XYZ.
That's OK. But what if I have n number of MarkdownEditor components and need isolated states for each of them? This is very basic problem, but how can I handle this?
I need a solution based on instances of module, not a module based one.
The module feature is to split the logic between different domains(Editor in your case is one module). Not for the instances themselves.
The rule of thumb is that the parent that will connect with the Vuex store passes down to MarkdownEditor.vue the data necessary to load. Ideally, MarkdownEditor is able to load just with the props received from the parent. This is a good practice of splitting the visual from the state. Making it easier to test and a clear component API.
Even though you have N possible ME(MarkdownEditor) instances, either you show one at once or multiple. For both cases, you can have a MarkdownEditorDataStore that will hold all the data needed.
Then you just need to access the correct piece of data for each ME instance. And that's up to your store and components structure. Two ways I can think of is that either you have an array for the N ME instance like editors: [ { id: 1, title: X}, { id: 2, title: Y } ] or an object that holds all the data { editors: { 1: {id: 1, title: X }, 2: { id: 2, title: Y } }.
Either you get the data via this.$store.state.MarkdownEditorDataStore.editors[myID]
or
this.$store.state.MarkdownEditorDataStore.editors.find(id => myID === id)
You can have a data property holding the currentEditorId in case you show just one instance at a time. Even better to use a getter in that case to show the actualCurrentEditorObject.
What i understand from your question is that you want a individual state for each component which you can achieve by creating a separate module with namespace=true
for each component
https://vuex.vuejs.org/guide/modules.html#namespacing

VueJS XHR inside reusable component

Asking for best practice or suggestion how to do it better:
I have 1 global reusable component <MainMenu> inside that component I'm doing XHR request to get menu items.
So if I place <MainMenu> in header and footer XHR will be sent 2 times.
I can also go with props to get menu items in main parent component and pass menu items to <MainMenu> like:
<MainMenu :items="items">
Bet that means I cant quickly reuse it in another project, I will need pass props to it.
And another way is to use state, thats basically same as props.
What will be best option for such use case?
If you don't want to instantiate a new component, but have your main menu in many places you can use ref="menu" which will allow you to access it's innerHTML or outerHTML. I've created an example here to which you can refer.
<div id="app">
<main-menu ref="menu" />
<div v-html="menuHTML"></div>
</div>
refs aren't reactive so if you used v-html="$refs.menu.$el.outerHTML" it wouldn't work since refs are still undefined when the component is created. In order to display it properly you would have to create a property that keeps main menu's HTML and set it in mounted hook:
data() {
return {
menuHTML: ''
}
},
mounted() {
this.menuHTML = this.$refs.menu.$el.outerHTML;
}
This lets you display the menu multiple times without creating new components but it still doesn't change the fact that it's not reactive.
In the example, menu elements are kept in items array. If the objects in items array were to be changed, those changes would be reflected in the main component, but it's clones would remain unchanged. In the example I add class "red" to items after two seconds pass.
To make it work so that changes are reflected in cloned elements you need to add a watcher that observes the changes in items array and updates menuHTML when any change is noticed:
mounted() {
this.menuHTML = this.$refs.menu.$el.outerHTML;
this.$watch(
() => {
return this.$refs.menu.items
},
(val) => {
this.menuHTML = this.$refs.menu.$el.outerHTML;
}, {
deep: true
}
)
}
You can also watch for changes in any data property with:
this.$refs.menu._data
With this you don't need to pass props to your main menu component nor implement any changes to it, but this solution still requires some additional logic to be implemented in it's parent component.

Why use props in react if you could always use state data?

I understand that there's two ways to pass components data: props and state. But why would one need a prop over a state? It seems like the state object could just be used inside the component, so why pass the prop parameters in markup?
Props are set externally by a parent component. E.g.;
render() {
return <ChildComponent someProp={someValue}/>;
}
State is set internally, and often triggered by an user event within a child. E.g.;
handleUserClickedButton: () {
this.setState({
buttonClicked: true
});
},
render() {
return <button onClick={this.handleUserClickedButton}/>;
}
So, props are a way for data to go from parent to child. State is a way for data to be managed within a singular component, and possibly have changes to that data triggered by children. In effect, they represent data traveling in 2 opposite directions, and the way in which they are passed is entirely unique.
There are two ways to "pass" or access data from outside your component but state is not one of them.
The two ways are:
Props - which a parent component pass down to the child component.
Context - which you can "skip" the direct parent in the tree.
The state is an internal object which no other component has access to it unless you pass it explicitly (via the two ways mentioned above).
So basically your question is not accurate as you can't really compare the two.
I think what you are really asking is why using a state-less instead of a state-full component.
Which you can find an answer here in Stack-overflow or in other websites.
Edit
A followup to some of your comments.
why does the child not just have a shared state? for example, each
component (or sub-component) could just do a "this.state" to get the
current state of the program
The same way you can't share or access private objects in other
functions.
This is by design, you share things explicitly and you will pass
only what the component needs. For example, look it this page of
stack-overflow, lets say the voting buttons are components, why
would i pass them the whole state if it only needs the vote count
and 2 onClick event listeners? Should i pass the current logged in
user or maybe the entire answers rendered in this page?
so you can't pass state between a parent to child? for example, can't
the parent change the state and then the child gets the new state
This is exactly what the props or context should do, provide an API for sharing data between parents and children though we keep it in a one way data flow, from parents to children, you can't pass props upwards. but you invoke handlers passed down to your child components and pass data through that handler.

How can a parent component communicate with a child component in Vue.js?

This is what I have:
<div id='vnav-container'>
<input type="text" v-model="searchTerm" v-on:keyup="search" class="vnav-input">
<menu :items="menu"></menu>
</div>
The outer component contains a search-input and a menu component.
When the user performs a search on the outer component, I need to call a method on the menu component, or emit an event, or whatever, as long as I can communicate to the menu component saying it should filter itself based on the new criteria.
I've read somewhere that calling methods on child components is discouraged and that I should use events. I'm looking at the docs right now, but I can only see an example of a child talking to a parent, not the other way around.
How can I communicate to the menu component as the search criteria changes?
EDIT
According to some blog posts, there used to be a $broadcast method intended to talk to child components but the documentation about that just vanished. This used to be the URL: http://vuejs.org/api/#vm-broadcast
The convention is "props down, events up". Data flows from parents to child components via props, so you could add a prop to the menu, maybe:
<menu :items="menu" :searchTerm="searchTerm"></menu>
The filtering system (I'm guessing it's a computed?) would be based on searchTerm, and would update whenever it changed.
When a system of components becomes large, passing the data through many layers of components can be cumbersome, and some sort of central store is generally used.
Yes, $broadcast was deprecated in 2.x. See the Migration guide for some ideas on replacing the functionality (which includes event hubs or Vuex).
Or you can create the kind of simple store for that.
First off, let's create the new file called searchStore.js it would just VanillaJS Object
export default {
searchStore: {
searchTerm: ''
}
}
And then in files where you are using this store you have to import it
import Store from '../storedir/searchStore'
And then in your component, where you want to filter data, you should, create new data object
data() {
return {
shared: Store.searchStore
}
}
About methods - you could put method in your store, like this
doFilter(param) {
// Do some logic here
}
And then again in your component, you can call it like this
methods: {
search() {
Store.doFilter(param)
}
}
And you are right $broadcast and $dispatch are deprecated in VueJS 2.0

Categories

Resources