Per the Svelte documentation on Props I am using props to pass a reference to the parent ponent to a child.
Props, short for 'properties', are the means by which you pass data down from a parent to a child ponent
That's exactly what I want to do. Here is a Svelte REPL with my code, that is also copied below:
My parent is 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'
}
},
ponents: {
Widget
}
};
</script>
The child ponent is 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>
Thanks to the props, the HTML <p>
elements can clearly reference the parent. However how can I reference the values in the parent ponent in the child ponent's JavaScript?
Per the Svelte documentation on Props I am using props to pass a reference to the parent ponent to a child.
Props, short for 'properties', are the means by which you pass data down from a parent to a child ponent
That's exactly what I want to do. Here is a Svelte REPL with my code, that is also copied below:
My parent is 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'
}
},
ponents: {
Widget
}
};
</script>
The child ponent is 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>
Thanks to the props, the HTML <p>
elements can clearly reference the parent. However how can I reference the values in the parent ponent in the child ponent's JavaScript?
1 Answer
Reset to default 8Inside lifecycle hooks and methods, access state with 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>
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744109082a4558865.html
评论列表(0条)