Vue.js中如何设置过滤器实现quotes数组theme字段的筛选功能?
修正方案
你现有代码存在几处逻辑错误,按以下修改即可实现主题筛选功能:
1. 错误梳理
- 模板中
v-for直接遍历原始quotes数组,没有关联过滤逻辑 - 过滤方法中误用赋值运算符
=代替全等判断===,且filter回调参数指向错误,无法获取当前遍历的quote项的theme值 - 每个主题单独定义过滤方法冗余,可通过统一逻辑简化处理
- 缺少接口请求触发逻辑,页面加载时不会自动拉取quotes数据
2. 修正后的模板代码
<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> <!-- 遍历过滤后的数组,而非原始quotes --> <div v-for="quote in filteredQuotes" v-bind:key="quote.id"> <p>Source: {{ quote.source }} </p> <p>Quote: {{ quote.quote }} </p> <p>Theme: {{ quote.theme }} </p> </div> </div> </div> </template>
3. 修正后的Script代码
<script> import axios from "axios"; export default { data: function () { return { message: "Welcome to Vue.js!", quotes: [], userFilterKey: "all", }; }, // 新增计算属性自动处理过滤 computed: { filteredQuotes() { // 全部主题直接返回原数组 if (this.userFilterKey === 'all') { return this.quotes } // 对应主题过滤,使用全等判断匹配theme字段 return this.quotes.filter(quote => quote.theme === this.userFilterKey) } }, methods: { quotesIndex: function () { axios // 替换为你的实际接口地址 .get("linktodata") .then((response) => { this.quotes = response.data; }); }, }, // 页面加载时触发接口请求 mounted() { this.quotesIndex() } } </script>
修改说明
- 用计算属性
filteredQuotes统一处理所有主题的过滤逻辑,不需要单独定义movies/games/books等重复的过滤方法,后续新增主题只需要加对应按钮即可,无需修改过滤逻辑 - 修复了原过滤逻辑的赋值、参数引用错误,正确匹配每一项quote的theme值
- 补充了mounted钩子触发接口请求,确保页面加载后能拿到数据
内容的提问来源于stack exchange,提问作者cckirk
相关产品推荐
相关产品推荐

