使用 Vue 过滤 JSON 响应

pad*_*lds 4 javascript vue.js axios

我正在练习将axios 与 Vue一起使用,但我认为这可能是一个更一般的 JSON 问题。

我已成功使用 axios 获取本地 products.json 文件,然后使用过滤器创建一个新数组,该数组仅包含具有匹配部门属性的产品,并将它们循环出去。

这是执行此操作的正确方法吗?或者我实际上可以过滤原始 axios 调用上的 JSON 结果吗?我知道我可以传递一个参数,该参数将依次执行特定的数据库调用,并且首先只提供所需的 JSON。

data(){
    return {
        products: []
    }
},
components: {
    Product
},
computed: {
    foodProducts(){
        return this.products.filter(x => x.department == 'Food')
    }
},
mounted() {
    axios
    .get('./json/products.json')
    .then(response => (this.products = response.data.products))
}
Run Code Online (Sandbox Code Playgroud)

谢谢。只是想澄清其背后的理论。

Ru *_*ong 5

根据您的情况或要求,它可以通过多种方式发挥作用。

你的方法有效。或者,您也可以直接从 API 调用中过滤结果,假设后端返回完整结果。

data() {
 return {
  filteredProducts: []
 }
}

mounted() {
 axios.get(API_URL)
  .then(response => {
   const products = response.data

   this.filteredProducts = products.filter(product => product.department.includes('food'))
  })
}
Run Code Online (Sandbox Code Playgroud)