我有一些网页组件创建使用发光元素。其中包括一些api请求,以便从另一个站点发送和获取数据,我希望通过api请求头发送一些数据。因此,我希望创建一个通用函数来包含这些标题细节,如果将来需要修改它们,我不需要一个一个地编辑这些组件。我需要这样的解决方案:
common_function.js
function api_request(url) {
// content
}my_component.js
import '/common_function.js';
...
constructor(){
api_request('http://apiRequestUrl');
}请让我知道一个方法来实现这一点,使用发光元素。提前谢谢。
发布于 2022-06-16 19:36:17
如何创建一个可以导入和重用的通用函数与lit无关。
因此,当您在一个名为“Common.js”的文件中有一个公共函数时:
export default txt => {
console.log('Hello from a common function!', txt);
}您可以在另一个javascript文件中使用它,包括lit组件,如下所示:
import commonfunction from '/path/to/your/common.js';
commonfunction('Wow!');什么可能是一个问题(但不是您的问题)是,您的浏览器没有导入点燃与您可能已经指定.因为它可能是您服务器上的npm包。即使您为node_modules文件夹提供服务并指定了确切的路径和文件名,您的lit导入也可能包括其他由于节点如何将它们指定为解析器而导致的其他导入。
因此,您可能需要使用类似于RollupJS的东西,它可以通过适当的导入来分发应用程序资源。请参阅https://rollupjs.org/guide/en/
希望这能有所帮助。
发布于 2022-01-29 14:00:49
好的..。我找到了解决办法。但我不知道这是否是完美的答案。我们可以使用发光反应控制器来完成这项工作。下面是我怎么做的例子。
common_function.js
import {initialState, Task} from '@lit-labs/task';
import * as SETTINGS from "../../bmw_settings";
export class ApiRequestController {
host;
url;
id;
task;
data = '';
_bmw_send_api_request() {
this.task = new Task(
this.host,
async ([data]) => {
const response = await fetch(
`${SETTINGS.BASE_URL + this.url}`,
{
headers: {
"Content-Type": "application/json",
'Access-Control-Request-Headers': 'Api-key, Content-Type',
'Api-key': '123'
}
}
);
const result = await response.json();
const error = result.error;
if (error !== undefined) {
throw new Error(error);
}
return result;
},
() => [this.data]
);
}
constructor(host, url, id) {
this.host = host;
this.url = url;
this.id = id;
this._bmw_send_api_request();
}
set data(value) {
this.data = value;
this.host.requestUpdate();
}
get data() {
return this.data;
}
render(renderFunctions) {
return this.task.render(renderFunctions);
}
}my_component.js
import { LitElement, html} from 'lit';
import {ApiRequestController} from '../../common_functions';
class search_bar extends LitElement {
static properties = {
provider_type : String,
reasons : Array,
}
constructor() {
super();
this._getAllReasons();
}
async _getAllReasons(){
this.reasons = await new ApiRequestController(this, '/api/v1/get-reasons', 'search_bar');
}
render() {
return html `
${this.reasons.render({
complete: (data) => html `
<p>Reasons List</p>
<select>
<option>Select Reason</option>
${data.data.map((val) =>
html `<option value="${val.id}">${val.reason}</option>`
)}
</select>
`,
})}
`;
}
}
customElements.define('search-bar', search_bar)如果需要更多详细信息,请使用这文档。谢谢
https://stackoverflow.com/questions/70903904
复制相似问题