簡體   English   中英

在 vue.js 中設置過濾器

[英]Setting up a filter in vue.js

創建過濾器以對報價數據進行排序,但在創建正確函數時遇到問題。

HTML:

<template>
  <div class="home">
    <h1>{{ message }}</h1>
    <h3> Theme filter: </h3>
    <div>
      <button v-on:click="userFilterKey = 'movies'"> Search movies</button>
      <button v-on:click="userFilterKey= 'all'"> Search all</button>
      <button v-on:click="userFilterKey= 'games'"> Search games </button>
      <div v-for="quote in quotes" v-bind:key="quote.id">
        <p>Souce: {{ quote.source }} </p>
        <p>Quote: {{ quote.quote }} </p>
        <p>Theme: {{ quote.theme }} </p>
      </div>
    </div>
  </div>
</template>

腳本:

import axios from "axios";
export default {
  data: function () {
    return {
      message: "Welcome to Vue.js!",
      quotes: [],
      userFilterKey: "all",
    };
  },
 methods: {
    userFilter: function () {
      return this[this.userFilterKey];
    },
    all: function () {
      return this.quotes;
    },
    movies: function () {
      return this.quotes.filter((theme) => (quotes.theme = "movies"));
    },
    books: function () {
      return this.quotes.filter((theme) => (quotes.theme = "books"));
    },
    quotesIndex: function () {
      axios
        .get("linktodata")
        .then((response) => {
          this.quotes = response.data;
        });
    },

如何創建過濾器以對鏈接中引號數組的主題鍵進行排序?

使用計算的 prop

 new Vue({ el: '#app', data: () => ({ quotes: [{ id: 1, source: 'a', quote: '', theme: '' }, { id: 2, source: 'b', quote: '', theme: 'movies' }, { id: 3, source: 'c', quote: '', theme: 'games' } ], userFilterKey: "all" }), computed: { filteredQuotes() { if (this.userFilterKey === 'all') { return this.quotes } return this.quotes.filter(v => v.theme === this.userFilterKey) } } })
 <div id="app"> <button @click="userFilterKey = 'all'"> Search all </button> <button @click="userFilterKey = 'movies'"> Search movies</button> <button @click="userFilterKey = 'games'"> Search games </button> <div v-for="quote in filteredQuotes" :key="quote.id"> <p>Souce: {{ quote.source }} </p> <p>Quote: {{ quote.quote }} </p> <p>Theme: {{ quote.theme }} </p> </div> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.14/vue.min.js"></script>

嘗試使用管道。 它在客戶端進行過濾並且速度更快。 可能會解決你的問題

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM