Vue计算值过滤器(脚本设置)

j2cgzkjk  于 2023-02-16  发布在  Vue.js
关注(0)|答案(1)|浏览(145)

我在网上找不到任何相关的东西。网上的相关答案没有使用标签。它甚至可以与脚本设置一起工作吗?

<template>
  <div class="bg-white md:container md:mx-auto w-10">
    <ul class="flex flex-wrap p-2 justify-center bg-black text-white">
      <li class="p-2">
        <a href=""> Filter </a>
      </li>
      <li class="p-2">
        <a href=""> Search </a>
      </li>
    </ul>

    <div class="flex flex-wrap justify-center h-52 content-center">
      <div class="flex justify-center">
        <div class="mb-3 xl:w-96">
          <label
            for="exampleSearch2"
            class="form-label inline-block mb-2 text-gray-700"
            >Search</label
          >
          <input
            v-model="searchValue"
            type="search"
            class="form-control block w-full px-3 py-1.5 text-base font-normal text-gray-700 bg-white bg-clip-padding border border-solid border-gray-300 rounded transition ease-in-out m-0 focus:text-gray-700 focus:bg-white focus:border-blue-600 focus:outline-none"
            id="exampleSearch2"
            placeholder="Type query"
          />
          <div class="flex flex-wrap">
            <div>Test: {{ searchValue }}</div>
          </div>
        </div>
      </div>
    </div>
    <div class="grid lg:grid-cols-4 md:grid-cols-3 gap-8">
      <dogCard v-for="breed in breedsArray" :key="breed.id" :breed="breed" />
    </div>
  </div>
</template>

<script setup>
import dogCard from "../components/dogCard.vue";
import { ref, onMounted, computed } from "vue";
import searchBox from "./searchBox.vue";

let URL = "https://api.thedogapi.com/v1/breeds";
const searchValue = ref("");
let breedsData = ref([]);

// Fetching API Data
function getBreedsArray() {
  fetch(URL)
    .then((response) => response.json())
    .then((data) => {
      breedsData.value = data;
      console.log("Data Fetched", breedsData.value);
    })
    .catch((error) => {
      console.error(error);
    });
}
onMounted(() => {
  getBreedsArray();
});

const breedsArray = computed({
  get() {
    return breedsData.value;
  },
  set(val) {
    breedsData.value = breedsData.value.filter((breed) => breed.name.includes() == searchValue);
  },
});
let isVisible = ref(false);
</script>

我试图通过一个搜索框过滤狗卡。我只是不知道如何做到这一点。数据的'breedsData'应该改变时,在搜索框中输入的东西。提前感谢,我卡住了这么久,现在,我不知道如何解决这个问题。

ppcbkaq5

ppcbkaq51#

在计算setter的filter()中,您可以执行以下操作:

(breed) => breed.name.includes() == searchValue

但是您可能希望使用ref的值而不是ref本身,并将其放入includes()

(breed) => breed.name.includes(searchValue.value)

请注意,这将永久删除过滤的breeds,因为您更改了breedsData.value。一个更好的方法可能是只使用计算的getter(我不认为setter以您希望的方式工作):

const breedsArray = computed(() => searchValue.value ? 
  breedsData.value.filter( breed => breed.name.includes(searchValue.value)) :
  breedsData.value
)

由于searchValue是被动的,因此对其的更改将触发breedsArray的更新。

相关问题