技术实践

使用 Vue3自定义过滤器

众所周知,在vue3.0中,删除了过滤器,那么,我们如何写一个高雅的过滤器

羊先生的头像
羊先生2021.11.10 · 1 分钟阅读 · 35 阅读
使用 Vue3自定义过滤器封面
文章正文还需 1 分钟

众所周知,在vue3.0中,删除了过滤器

那么,我们如何写一个高雅的过滤器

html 复制代码
<template>
  <div>
    <input
      type="text"
      :value="value"
      @input="$emit('input', $event.target.value)"
    />
  </div>
</template>

<script>
export default {
  name: "FilterComponent",
  props: {
    value: String,
  },
};
</script>

在上面的代码中,我们将输入的输入值绑定到该值,该值被定义为类型为 string 的 prop,并发出输入事件。

现在转到要在其中使用此自定义 FilterComponent 的文件,并添加下面的代码。我要把它添加到 App.vue 中。

html 复制代码
<template>
  <div id="app">
    <div class="text-left">
      <h3>Cutsom Filter using VueJs</h3>
      <FilterComponent v-model="search" />
      <ul v-for="user in searchResult" :key="user.id">
        <li>{{ user.name }}</li>
      </ul>
    </div>
  </div>
</template>

<script>
import FilterComponent from "./components/FilterComponent";

export default {
  name: "App",
  components: {
    FilterComponent,
  },
  data() {
    return {
      search: null,
      users: [
        { id: 1, name: "john", email: "john@xyz.com" },
        { id: 2, name: "lee min", email: "leemin@xyz.com" },
        { id: 3, name: "alexa", email: "alexa@xyz.com" },
        { id: 4, name: "rosy", email: "rosy@xyz.com" },
        { id: 5, name: "joy", email: "joy@xyz.com" },
        { id: 6, name: "john", email: "john@vue.com" },
      ],
    };
  },
  computed: {
    searchResult() {
      if (this.search) {
        return this.users.filter((item) => {
          return this.search
            .toLowerCase()
            .split(" ")
            .every((v) => item.name.toLowerCase().includes(v));
        });
      } else {
        return this.users;
      }
    },
  },
};
</script>
html 复制代码
<style>
#app {
  font-family: "Avenir", Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
.text-left {
  text-align: left;
}
input {
  padding: 7px;
  border-radius: 4px;
  border: 1px solid gray;
  box-shadow: 7px 7px 19px -6px rgba(0, 0, 0, 0.72);
  -webkit-box-shadow: 7px 7px 19px -6px rgba(0, 0, 0, 0.72);
  -moz-box-shadow: 7px 7px 19px -6px rgba(0, 0, 0, 0.72);
}
</style>

在线演示