组件中,如果是父组件和后代组件通讯 #9
Replies: 4 comments
-
|
还有下面几个方案: <!--父组件-->
<template component>
<div class="container" on:custom-event="someFunc">
<!--存放后代组件的地方-->
...
</div>
<script>
...
proto:{
someFunc(event){
const {
data // 获得到的数据
} = event;
// do something
}
}
...
</script>
</template><!--后代组件-->
<template component>
<button on:click="haha">Click Me</button>
<script>
...
proto:{
haha(){
this..emit("custom-event",{
composed: true,
data:{
// 你的自定义数据
}
});
}
}
...
</script>
</template> |
Beta Was this translation helpful? Give feedback.
-
|
还有几个比较粗暴的方法,直接通获取后代组件或父组件,进行交互:
<!--父组件-->
<template component>
<script>
...
proto:{
xxxx(data){
// do something
}
}
...
</script>
</template><!--后代组件-->
<template component>
<button on:click="haha">Click Me</button>
<script>
...
tag:"sub-ele",
proto:{
haha(){
this.host.xxxx('some data'); // 直接让一级父组件运行它的方法
// this.host.host.xxxx('some data'); // 直接让二级父组件运行它的方法,以此类推
}
}
...
</script>
</template>
<!--父组件-->
<template component>
<button on:custom-event="someFunc">主动运行后代组件的方法</button>
<div class="container">
<!--存放后代组件的地方-->
<sub-ele></sub-ele>
...
</div>
<script>
...
proto:{
someFunc(event){
this.shadow.$('sub-ele').xxxx('some data'); // 直接运行子组件的方法
// this.shadow.$('sub-ele').shadow.$('sub-ele-two').xxxx('some data'); // 多级查找子组件,并主动运行方法,以此类推
}
}
...
</script>
</template> |
Beta Was this translation helpful? Give feedback.
-
|
从4.5.0 开始,可以使用 由于官网还在重构中,当前 api 需要查看测试用例来参考使用。 https://github.com/kirakiray/ofa.js/tree/main/test/cases/context |
Beta Was this translation helpful? Give feedback.
-
|
当 ofa.js 版本更新至 4.5.0 以上时,可以通过使用 示例代码如下: ...
<l-m src="./comp-one.html"></l-m>
<o-provider name="yourKey" custom-a="I am A" custom-b="I am B">
<comp-one></comp-one>
<div>
<o-consumer name="yourKey">consumer child</o-consumer>
</div>
</o-provider>
...在子组件内部,我们可以通过在 例如,在 <!-- comp-one.html -->
<template component>
<o-consumer name="yourKey" watch:custom-a="ca">
provider in shadow
</o-consumer>
<script>
export default {
tag: 'comp-one',
data: {
ca: null, // 初始值设置为 null
},
};
</script>
</template>上述代码中, |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
组件中,如果是父组件和后代(孙组件)组件通讯,只能一层一层通过proto传递的通讯吗
Beta Was this translation helpful? Give feedback.
All reactions