问题
I made a BlogList.vue
component which list all the blog teasers.
I made a search box in the BlogList.vue
component:
<input type="text" placeholder="Enter key word" v-model="search">
With a computed property I build the search filter based on what the user types in the search field:
computed: {
getfilteredData() {
return this.experiences.filter(experience =>
experience.name.toLowerCase().includes(
this.search.toLowerCase()
)
)
}
},
This all works fine.
But I like to move the search box to a separate component SearchBlogs.vue
.
In this component I tried it with EventBus
and $emit
the search value:
methods: {
emitSearchValue() {
EventBus.$emit('search-value', 'this.search')
}
Because I don't want the user to e.g. click a search button (I want as soon as they type something it's filtering the list), I don't know how to $emit
the event?
Now I have in the <template>
section of the Search component:
<input
type="text"
v-model="search"
@change="emitSearchValue"
placeholder="search experience"
>
What do I have to do, to make the communication between those components work?
Update:
Here is the link to the codesandbox
回答1:
Look at my solution condesandbox
Here is an explanation:
You don't need to use EventBus. You can communicate with Search Component by v-model
, using prop value
and emiting updated value
from the Input.
Then your Main (List) Component is responsible for all the logic.
- It keeps the state of a Search
- It keeps the items and filtered Items
Thanks to that your Search Component is very clear and has no data, that means it has very little responsibility.
Please ask questions if I can add something to help you understand 😉
UPDATE:
- EventBus is a great addition in some cases. Your case is simple enough, there is no need to add it. Right now your architecture is "over engineered".
- When you have added listener on EventBus, on
created:hook
you should always remove it while Component is beingdestroyed
. Otherwise you can encounter a trouble with double calling function etc. This is very hard to debug, tryst me I'he been there 😉 - Going with my suggestion gives you comfort of "no-need-to-remember-about-this" because Vue is doing it for you.
Hope that help.
回答2:
Couple of issues but essentially the computed prop filteredData
will look like:
computed: {
filteredData() {
return this.experiences.filter(
el => el.category.indexOf(this.search) > -1
);
}
}
Also, used quotes around 'this.search'
when passing its value back which made it a string.
Fixed sandbox
https://codesandbox.io/s/reverent-lamarr-is8jz
来源:https://stackoverflow.com/questions/62365339/move-vue-js-search-functionality-to-separate-component-and-how-to-emit-the-event