问题是,如何从子组件调用方法?
例如:考虑我有一个位于父组件中的登录表单组件。因此,当我单击登录按钮时,我需要显示该表单。显示登录表单的功能将编写在父组件中,当我单击位于子组件中的按钮时,我需要使用该功能。
这是父组件
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
}
}