在 Vue js 中将函数作为 prop 传递以获取数据

Passing a function as a prop in Vue js to fetch data

我有一个组件,我想将其与获取数据的实现分离。这样我就可以将获取数据回调作为道具传递。

我想这样做,以便我可以在故事书中模拟获取数据。

Request.js

export const endpoints = {
  fetchProducts: page => `https://some-end-point-here?page=${page}`
};

export const fetchProducts = async (page = 1, endpoint = endpoints.fetchProducts(1)) => {
  const response = await fetch(endpoint);
  return await response.json();
}; 

(storybook) 组件被使用的地方

import {fetchProducts} from "./request";
export const someCPM = ()=> ({
    components: {SomeCPM},
    props: {
        fetchProducts: {default: fetchProducts},
    },
    template: `<product-grid v-bind="$props"></product-grid>`
});

组件的道具类型

  fetchProducts: {
    type: Function,
    required: true
  }

问题是我不断收到关于错误道具类型的警告。这意味着它正在获得承诺。 因此未能执行为获取产品不是函数。

即使将 fetchProducts 设为 return 编号并删除异步性质,如下所示:

const fetchProducts = () => 9999

然后我得到 fetch product 是一个数字,而不是一个函数! 这意味着即使我正在将 reference 传递给正在以某种方式执行的函数。

我不得不使用工厂函数来让它工作。

export const fetchProducts = () => async (page = 1, endpoint = endpoints.fetchProducts(1)) => {
  const response = await fetch(endpoint);
  return await response.json();
};