3
votes

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

3

3 Answers

4
votes

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.

1
votes

Yes, $broadcast was deprecated in 2.x. See the Migration guide for some ideas on replacing the functionality (which includes event hubs or Vuex).

1
votes

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