[Vuejs]-How do I have a vue component update a list in another component that is not its child?

0👍

You should try to follow a one-way data flow paradigm. In this instance, the <filter-controls> should be $emiting up events as you type or, you can leverage v-model in your component. It sounds similar to the <custom-input> in the example in the docs: Using v-model on Components.

Once your parent component understands that the filtering needs to be adjusted due to the received event, it can either change a prop that is passed to the <data-list> that is used to know what to filter by, or if you are passing the list of items directly to <data-list>, you can filter in the parent and the <data-list> will re-render do to the list changing.

The main thing with Vue, as well as other "reactive" libraries is that you need to try to keep to the tenent:

data down, props up.

Children shouldn’t mutate their parents data. They should tell their parents about something and the parent should do something about it. Otherwise it can become difficult to reason about who is responsible for what data.


If you feel that passing events becomes either unmanageable, or their are too many cross-cutting components, you might want to consider using a store-like pattern. Vue has the Vuex library to help with this and also discusses some of the things to consider in the docs: State Management.

0👍

zero298’s answer is fine as it goes, but I think in this particular case, there’s a slightly different approach that you might prefer.

  • First, since <filter-controls> and <data-list> are linked together, create a master component that includes one of each, maybe <filtered-data-list>.

  • Second, construct your custom <filter-controls> component so that it uses a value property and @input events. That will make it compatible with Vue’s v-model directive.

  • In the parent <filtered-data-list> component, pass the relevant object to <filter-controls> using v-model. That way, the object will automatically update when the user changes the controls.

  • Also, in the parent, create a computed property, say filteredData, that takes the full data set and applies the appropriate filters to generate a new data set.

  • Finally, pass this computed property to the <data-list> component.

Leave a comment