【问题标题】:vue: how to filter data from arrayvue:如何过滤数组中的数据
【发布时间】:2020-12-12 23:20:00
【问题描述】:

我是 Vue 的新手,我正在使用 API 来显示数据,在我的代码中,当单击到类别时,它会保存该类别的名称并将用户重定向到另一个名为 category.vue 的页面,我的问题是在重定向用户之后我现在想显示仅收到的具有该类别名称的问题(作为过滤器),有没有办法做到这一点?

  
  /* this is how i saved data to transfer to category page */
  
  <div class="category" v-for="(categoryy,index) in category(question1)" :key="index">
   <router-link :to="`/category/${category(question1)}`"> {{ categoryy }} </router-link>
    
       </div> 

category.vue

<template>
  
    <div class="vw">
   <p> related question of </p>
    
  <p>{{ this.$route.params.cat }}</p> /* category name i sent appears here */
       
     <ul class="container-question" v-for="(question1,index) in questions" :key="index"  

  >
/* THE PROBLEM : it shows all questions without filtering */
  
     {{question1.question}}
         </ul>
    </div>
 
</template>
<script>
export default {
    
    props:
{
    question1: Object
},
data(){
    return{
questions: []
    }
    


},
computed:{
    category(){
        let category = this.$route.params.cat;
        return category
    }
},
mounted: function(){
fetch('https://opentdb.com/api.php?amount=10&category=9&difficulty=medium&type=multiple',{
  method: 'get'
})
.then((response) => {
  return response.json()
})
.then((jsonData) => {
  this.questions = jsonData.results
})
  }
}
</script>

【问题讨论】:

    标签: javascript html vue.js


    【解决方案1】:

    你可以先用这条路线https://opentdb.com/api_category.php获取所有类别 我怀疑你已经在第一个 vue 页面上完成了。

    然后,您将类别的 id 作为路由参数传递。

    您似乎在这里唯一想念的是您已在挂载的 fetch 中硬编码类别 id 9。

    您希望将其更改为:

    fetch(`https://opentdb.com/api.php?amount=10&category=${this.category}&difficulty=medium&type=multiple`,{
      method: 'get'
    })
    

    这种方式使用您在上一页的路由器参数中创建的计算属性。

    【讨论】:

    • 这将只显示我点击的类别,我想要显示与我点击的类别相关的所有问题
    • 什么意思?这将显示与您单击的类别相关的所有问题。例如,this.category = 9; - opentdb.com/…这个列表不代表你想要的数据吗?
    【解决方案2】:

    你必须不通过计算属性传递路由参数,而是直接在挂载的钩子上传递,

    export default {
      mounted() {
        fetch(
          `https://opentdb.com/api.php?amount=10&category=${this.$route.params.cat}&difficulty=medium&type=multiple`,
          {
            method: "get",
          }
        )
          .then((response) => response.json())
          .then((jsonData) => (this.questions = jsonData.results));
      },
    };
    
    

    【讨论】:

    • 这将只显示我点击的类别,我想要显示与我点击的类别相关的所有问题
    猜你喜欢
    • 2021-03-07
    • 1970-01-01
    • 2022-10-15
    • 2018-01-26
    • 1970-01-01
    • 2018-05-24
    • 1970-01-01
    • 1970-01-01
    • 2023-01-03
    相关资源
    最近更新 更多