【问题标题】:vue filtering values from JSON with computed-functionvue 使用计算函数从 JSON 过滤值
【发布时间】:2021-01-21 12:58:23
【问题描述】:

如何过滤我的 JSON 数据数组:

这是我的标记:

  <div v-if="vacciCounter">
        <b-card no-body class="mb-2" v-for="(stateObject, state) in filteredList" v-bind:key="state">

            <div style="margin:10px 10px 10px 10px;">
                <h5>{{ state }}</h5>

这是我的功能:

  computed: {
        filteredList() {
            if (this.vacciResults.length > 0) {  
                return this.vacciResults.filter(entry => {
                    return entry.state.toLowerCase().includes(this.searchstring.toLowerCase())

                });
            } 
        },
      
        getStates() {
         return this.vacciResults; // assuming that you have stored the response in a variable called 'output' defined in the data section
           }    

这是我获取 JSON 数据的 API 函数:vacciResults 正在获取状态。

fetch(vacciURL, {
        method: 'get',
        headers: {

        }

        }).then(res => res.json())
        .then(res => {

            this.status = '';
            this.searchBtnDisabled = false;
            

            this.vacciCounter = res.vaccinated;
            this.vacciResults = res.states;

【问题讨论】:

  • vacciResults ...那是你的响应对象吗?
  • 是的,这是响应对象:this.vacciResults = res.states;
  • 在您的问题中也添加该代码

标签: javascript vue.js


【解决方案1】:

这里的问题是

this.vacciResults 是一个对象,您在计算属性中尝试对其进行数组操作

下面是修改后的计算属性


     computed: {
            filteredList() {
    //********* changes added below ***********
                if (this.searchString !== '' && Object.keys(this.vacciResults).length > 0) { 
                      let filterObject = {};           
                      Object.keys(this.vacciResults).forEach(state => {
                          if(state === this.searchString.toLowerCase()) filterObject[state] = this.vacciResults[state];
                      });
                  return filterObject;
                 }
             return this.vacciResults;              
            },
          
            getStates() {
             return this.vacciResults; // assuming that you have stored the res.states in a variable called 'vacciResults' defined in the data section
             }  
      }

【讨论】:

  • 哇,太棒了!我马上试试。 THX
  • 不幸的是,它不起作用。列表不显示:(
  • 尝试在您的计算属性中打印 this.vacciResults、this.searchString 的控制台日志
  • 好的,试过了。列表中未显示任何结果。
  • 那么为了得到更多的理解,请在问题中分享文件的整个代码
猜你喜欢
  • 2016-10-31
  • 2018-02-12
  • 2020-10-19
  • 1970-01-01
  • 2019-05-25
  • 2012-07-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多