【发布时间】:2020-10-03 12:20:37
【问题描述】:
我有以下组件:
/components/SearchBlogs.vue 搜索组件以过滤 blog.title 和 blog.description。
/components/BlogList.vue这里我列出了所有的博客项目。
SearchBlogs.vue
<template>
<div>
<input type="text" v-model="search" @change="emitSearchValue" placeholder="search blog">
</div>
</template>
<script>
import { EventBus } from '../event-bus.js'
export default {
name: 'SearchBlogs',
data: () => {
return {
search: ''
}
},
methods: {
emitSearchValue() {
EventBus.$emit('search-value', 'this.search')
}
}
}
</script>
BlogList.vue
<template>
<div>
<div v-for="blog in filteredBlogs" :key="blog">
<BlogListItem :blog="blog" />
</div>
</div>
</template>
<script>
import BlogListItem from './BlogListItem'
import { EventBus } from '../event-bus.js'
export default {
name: 'BlogList',
components: {
BlogListItem,
},
data: () => {
return {
blogs: [],
searchvalue: ''
}
},
computed: {
filteredBlogs() {
return this.blogs.filter(blog =>
blog.name.toLowerCase().includes(
this.searchvalue.toLowerCase()
)
)
}
},
created() {
fetch('http://localhost:3000/blogs')
.then(response => {
return response.json();
})
.then(data => {
this.blogs = data;
}),
EventBus.$on('search-value', (search) => {
this.searchvalue = value;
})
}
}
</script>
在另一个页面组件博客我注册了两个组件:
<template>
<div>
<h1>Blog</h1>
<TheSidebar>
<SearchBlogs />
</TheSidebar>
<BlogList/>
</div>
</template>
任何人都可以看到这里缺少什么吗?我希望,一旦用户在搜索输入(来自SearchBlogs.vue 组件)中输入内容,它就会开始过滤和更新列表。
【问题讨论】:
-
嘿伙计,添加codesandbox我会为你编辑它并提供解决方案。
-
@Adam Orlov 这是codesandbox的链接希望你能弄清楚,非常感谢!
-
你想使用 EventBus 吗?没有必要。可以用它来完成,但没有意义。
-
我已经更新了我的答案。
标签: vuejs2 vue-component v-for computed-properties