javascript - 在 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 是一个数字,而不是一个函数!这意味着即使我在某处传递对函数的引用,它正在以某种方式被执行。
解决方案
我必须使用工厂功能才能使其工作。
export const fetchProducts = () => async (page = 1, endpoint = endpoints.fetchProducts(1)) => {
const response = await fetch(endpoint);
return await response.json();
};
推荐阅读
- python - Python:如何编写一个函数来打印'height'行,每行都有'sym'重复'length'次?
- python - 读取多个txt文件python
- vue.js - 使用没有角度的清晰设计日期选择器
- python - Python - Tkinter.Listbox <
> 不工作 - swift - 当我使用可可豆荚在物理设备上运行应用程序时崩溃
- ios - 我是否需要在 Apple 上使用订阅或消耗性 IAP
- javascript - 浏览对象数组并删除对象
- reactjs - 如何更改材质 UI 选择边框和标签
- powershell - 使用函数参数作为变量和开关
- javascript - 使用 Javascript 按字母顺序设置选择