如何引用 Svelte 组件的 parent 组件?
How do I reference a Svelte component's parent component?
根据 Svelte documentation on Props,我正在使用道具将对 parent 组件的引用传递给 child。
Props, short for 'properties', are the means by which you pass data down from a parent to a child component
这正是我想要做的。这里是a Svelte REPL with my code,也复制如下:
我的parent是App.html:
<div class='widget-container'>
<Widget foo bar="static" {baz}/>
</div>
<script>
import Widget from './Widget.html';
export default {
data: function(){
return {
baz: 'click me and check the console'
}
},
components: {
Widget
}
};
</script>
child分量是Widget.html:
<p>foo: {foo}</p>
<p>bar: {bar}</p>
<p>baz: {baz}</p>
<script>
export default {
oncreate: function(){
window.document.body.addEventListener('click', function(event){
console.log(`Clicked!, ${baz}`)
});
}
}
</script>
感谢道具,HTML <p>
元素可以清楚地引用 parent。但是如何在child组件的JavaScript中引用parent组件中的值?
内部生命周期挂钩和方法,访问状态 this.get()
:
<p>foo: {foo}</p>
<p>bar: {bar}</p>
<p>baz: {baz}</p>
<script>
export default {
oncreate: function(){
window.document.body.addEventListener('click', () => {
const { baz } = this.get();
console.log(`Clicked!, ${baz}`)
});
}
}l
</script>
根据 Svelte documentation on Props,我正在使用道具将对 parent 组件的引用传递给 child。
Props, short for 'properties', are the means by which you pass data down from a parent to a child component
这正是我想要做的。这里是a Svelte REPL with my code,也复制如下:
我的parent是App.html:
<div class='widget-container'>
<Widget foo bar="static" {baz}/>
</div>
<script>
import Widget from './Widget.html';
export default {
data: function(){
return {
baz: 'click me and check the console'
}
},
components: {
Widget
}
};
</script>
child分量是Widget.html:
<p>foo: {foo}</p>
<p>bar: {bar}</p>
<p>baz: {baz}</p>
<script>
export default {
oncreate: function(){
window.document.body.addEventListener('click', function(event){
console.log(`Clicked!, ${baz}`)
});
}
}
</script>
感谢道具,HTML <p>
元素可以清楚地引用 parent。但是如何在child组件的JavaScript中引用parent组件中的值?
内部生命周期挂钩和方法,访问状态 this.get()
:
<p>foo: {foo}</p>
<p>bar: {bar}</p>
<p>baz: {baz}</p>
<script>
export default {
oncreate: function(){
window.document.body.addEventListener('click', () => {
const { baz } = this.get();
console.log(`Clicked!, ${baz}`)
});
}
}l
</script>