[英]Setting up a filter in vue.js
Creating a filter to sort through quotes data, but having problems with creating the correct functions.创建过滤器以对报价数据进行排序,但在创建正确函数时遇到问题。
HTML: 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>
Script:脚本:
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;
});
},
How do I create filters to sort through the theme key of the quotes array within my link?如何创建过滤器以对链接中引号数组的主题键进行排序?
Use a computed prop .使用计算的 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>
Try using Pipes.尝试使用管道。 Its something that does the filter in client side and is faster.
它在客户端进行过滤并且速度更快。 may be that solves your problem
可能会解决你的问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.