首页 > 解决方案 > 在 Vue js 中将函数作为道具传递以获取数据

问题描述

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

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

请求.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();
}; 

(故事书)使用组件的位置

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
  }

问题是我不断收到有关错误道具类型的警告。这意味着它正在获得 Promise。因此,未能作为 fetch products 执行不是一项功能。

即使让 fetchProducts 返回数字并删除异步性质,如下所示:

const fetchProducts = () => 9999

然后我得到那个 fetch product 是一个数字,而不是一个函数!这意味着即使我在某处传递对函数的引用,它正在以某种方式被执行。

标签: javascriptvue.jsstorybook

解决方案


我必须使用工厂功能才能使其工作。

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

推荐阅读