使用EventBus通过单个文件组件传递Vue js搜索筛选器功能 [英] Pass Vue js search filter functionality through single file components with EventBus

查看:8
本文介绍了使用EventBus通过单个文件组件传递Vue js搜索筛选器功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下组件:

/components/SearchBlogs.vue筛选blog.titleblog.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组件)中键入内容,它就会开始筛选和更新列表。

推荐答案

查看我的解决方案condesandbox

以下是一个解释: 您不需要使用EventBus。您可以通过v-model、使用属性value和从输入发出更新的value与搜索组件进行通信。

然后您的主(列表)组件负责所有逻辑。

  1. 它保持搜索的状态
  2. 保留项目和筛选的项目

由于您的搜索组件非常清晰且没有数据,这意味着它几乎没有责任。

如果我可以添加一些内容来帮助您了解😉,请提问

更新

  1. 在某些情况下,EventBus是一个很好的补充。你的理由很简单,没有必要再加了。目前,您的体系结构是"过度设计的"。
  2. created:hook的EventBus上添加侦听器后,应始终在组件destroyed时将其删除。否则你可能会遇到双重调用函数等问题。这很难调试,请见见我他在那里😉
  3. 接受我的建议会让你感到"不需要记住这件事",因为Vue是为你做的。

希望能有所帮助。

这篇关于使用EventBus通过单个文件组件传递Vue js搜索筛选器功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆