0

问题是,如何从子组件调用方法?

例如:考虑我有一个位于父组件中的登录表单组件。因此,当我单击登录按钮时,我需要显示该表单。显示登录表单的功能将编写在父组件中,当我单击位于子组件中的按钮时,我需要使用该功能。

这是父组件

import Nav from './componets/navigation-bar.js'
import Comp from './componets/footer.js'
import UserComp from './componets/user-comp.js'

import Base from './componets/Base.js'

const style = `
    .container {
        display: flex;
        flex-direction: row;
        justify-content: center;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
    }

    .container > user-comp {
        padding: 1em;
    }

`
const content = `
<navigation-bar></navigation-bar>
    <div class="container">
        <user-comp mirror="true">
            <img slot="image" src="https://www.zricks.com/img/UpdatesBlog/44b94c9d-ab13-401d-9e5b-86a00f9da6496%20Must%20Follow%20Tips%20to%20Market%20a%20Luxury%20Home.jpg" alt="Image"></img>
            <h1 slot="title">Rent or Lease your own property</h1>
        </user-comp>
        <user-comp mirror="true">
            <img slot="image" src="https://s3.amazonaws.com/clients.granalacantadvertiser.images/wp-content/uploads/2017/06/14072232/2236775_2_O.jpg" alt="Image"></img>
            <h1 slot="title">Looking for a place</h1>
        </user-comp>
    </div>
<footer-c></footer-c>
`

export default class UI extends Base {
    constructor() {
        super()

        this.render(style, content)
        this.attachShadow({ mode: 'open' })
        this.shadowRoot.appendChild(this.template.content.cloneNode(true))
    }
    clicked = () => {
        console.log('clicked')
    }
}
window.customElements.define('ui-c', UI)

document.querySelector('#root').innerHTML = '<ui-c></ui-c>'

这是子组件

import Base from './Base.js'

const style = `
    header {
        position: absolute;
        top:0;
        left:0;
        right:0;
        background-color: #111111;
        color: #eeeeee;
        z-index:1;
    }
    
    .logo {
        margin-left: 2em;
    }

    nav {
        display: flex;
        flex-direction: row;
        justify-content: space-between;
    }

    #login-button {
        height: 2.5em;
        width: 10em;
        margin: auto 2em;
        text-transform: uppercase;
        color: #eeeeee;
        background-color: #239710;
        border: none;
        box-shadow: 1px 1px 5px 1px rgba(23,97,10,0.64);
        outline: none;
        cursor: pointer;
        transition: 0.4s;
    }
    
    #login-button:hover {
        background-color: #34a832;
    }

`
const content = `
    <header>
        <nav>
            <h3 class="logo">Homey</h3>
            <button id="login-button"> login </button>
        </nav
    </header>
`

export default class Nav extends Base {
    constructor() {
        super()
        this.render(style, content)
        this.attachShadow({ mode: 'open' })
        this.shadowRoot.appendChild(this.template.content.cloneNode(true))
    }

    connectedCallback() {
        this.shadowRoot
            .querySelector('#login-button')
            .addEventListener('click', clicked())
    }
}
window.customElements.define('navigation-bar', Nav)

这是我写的Base类(以防万一)

export default class Base extends HTMLElement {
    template = document.createElement('template')

    style(style) {
        if (style === null) return ' '
        return '<style>' + style + '</style>'
    }
    render(style, content) {
        if (content === null) content = ''
        this.template.innerHTML = this.style(style) + content
    }
}
4

2 回答 2

1

您可以使用事件将数据从子组件传递到父组件。

在您的子组件中,您可以创建一个自定义事件并在您想要调用父组件上的方法时启动它。

// create and dispatch the event
var event = new CustomEvent("cat", {
  detail: {
    hazcheeseburger: true
  }
});
obj.dispatchEvent(event);

然后在您的父组件中,您可以侦听该事件。一旦事件被触发,事件监听器将捕获并相应地继续。它看起来像这样。

obj.addEventListener("cat", function(e) { process(e.detail) });

示例取自MDN 网络文档

于 2020-08-19T08:34:53.300 回答
0

事件是防止组件之间紧密耦合的一个很好的解决方案。但需要一些工作。

有时你只知道你需要 DIV 元素 3 层上/下 DOM

向上 DOM

标准element.closest(selector)“走”上 DOM 以找到您所追求的选择器。

https://developer.mozilla.org/en-US/docs/Web/API/Element/closest

.closest()不会逃脱shadowDOM

为此,您必须编写一个closestNode(selector)遍历所有 shadowDOM 的递归函数,.getRootNode()直到找到选择器

customElements.define("my-element", class extends HTMLElement {

  closestNode(
    selector, // selector like in .closest()
    start = this, // extra functionality to skip a parent
    closest = (el, found = el && el.closest(selector)) =>
    !el || el === document || el === window 
      ? null // standard .closest() returns null for non-found selectors also
      : found || closest(el.getRootNode().host) // recursion!! break out to parent DOM
  ) {
    return closest(start); // look from start
  }

  connectedCallback() {
    this.attachShadow({
           mode: 'closed'// just to show it works with closed mode
         }).append(document.getElementById(this.nodeName).content.cloneNode(true));

    this.onclick = (evt) => {
      evt.stopPropagation();
      let container = this.closestNode('div');
      let color = evt.target.childNodes[0].nodeValue;
      container.style.background = color;
    }
  }
})
<template id=MY-ELEMENT>
  <style>
    button {
      font: 16px Arial, sans;
      margin:.5em;
    }
    button:hover{
      background:lightgreen;
    }
  </style>
  <button><slot></slot></button>
</template>
<div>
  <my-element>red
    <my-element>green
      <my-element>orange
        <my-element>blue
          <my-element>yellow
            <my-element>hotpink
            </my-element>
          </my-element>
        </my-element>
      </my-element>
    </my-element>
  </my-element>
</div>

向下 DOM

您想阻止但有时会派上用场的事情

  const shadowDive = (
          el, 
          selector, 
          match = (m, r) => console.warn('match', m, r)
  ) => {
    let root = el.shadowRoot || el;
    root.querySelector(selector) && match(root.querySelector(selector), root);
    [...root.children].map(el => shadowDive(el, selector, match));
  }
于 2020-08-19T09:14:08.587 回答