首页 > 解决方案 > 使用 EventBus 通过单个文件组件传递 Vue js 搜索过滤器功能

问题描述

我有以下组件:

/components/SearchBlogs.vue要过滤的搜索组件blog.titleblog.description

/components/BlogList.vue在这里,我列出了所有的博客项目。

搜索博客.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>

博客列表.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组件)中输入内容,它就会开始过滤和更新列表。

标签: vuejs2vue-componentv-forcomputed-properties

解决方案


几个问题,但本质上计算的道具filteredData看起来像:

computed: {
    filteredData() {
      return this.experiences.filter(
        el => el.category.indexOf(this.search) > -1
      );
    }
}

此外,在将其值传回时使用了引号,'this.search'这使它成为一个字符串。

固定沙箱

https://codesandbox.io/s/reverent-lamarr-is8jz


推荐阅读