我正在使用 web 组件和 vanilla javascript 构建一个项目。
我有一个名为的组件/模块meal.module
- 它是组件的父组件,meal-list
并且meal-search
.
- 膳食列表显示来自 api 的多餐。
- meal-search 包含一个输入字段和 seachterm 作为属性。
餐.module.js
export default class MealModule extends HTMLElement {
connectedCallback() {
this.innerHTML = '<mp-meal-search searchterm=""></mp-meal-search> ' +
'<mp-meal-list></mp-meal-list> ' +
}
}
if (!customElements.get('mp-meal-module')) {
customElements.define('mp-meal-module', EssenModule);
}
餐单.component
export default class MealListComponent extends HTMLElement {
connectedCallback() {
this.attachShadow({mode: 'open'});
this.shadowRoot.innerHTML = Template.render();
// Renders the meals from api into the template
this.getMeals();
}
(....) more code
}
if (!customElements.get('mp-meal-list')) {
customElements.define('mp-meal-list', MealListComponent);
}
膳食搜索.component
export default class MealSearchComponent extends HTMLElement {
static get observedAttributes() {
return ['searchterm'];
}
attributeChangedCallback(name, oldVal, newVal) {
if (name === 'searchterm') {
this.doSearch();
}
}
set searchTerm(val) {
this.setAttribute('searchterm', val)
}
get searchTerm() {
return this.getAttribute('searchterm');
}
constructor() {
super();
this.attachShadow({mode: 'open'});
this.shadowRoot.innerHTML = '<input type="text" id="searchterm" value=""/>'
this.shadowRoot.addEventListener('change', (event) =>
this.searchTerm = event.target.value
)
}
doSearch() {
// send signal to MealListComponent for search
}
}
if (!customElements.get('mp-meal-search')) {
customElements.define('mp-meal-search', MealSearchComponent);
}
在 seach-component 中,SearchTerm 被配置为属性。每次输入字段更改时,属性也会更改。
现在我想实现一个“searchMeal”函数,它总是在 MealSearchComponent 中的属性发生变化时触发。
我已经尝试将其导入MealSearchComponent
MealListComponent。但它似乎确实打破了组件的规则,没有任何依赖关系。