需求描述
随着开发的深入和代码的维护,为了某些功能的实现可以说是又秃了几根;接下来就说一说,通过 ref 实现父组件调用子组件的方法等。
1.父组件模板
在父级模块的子组件上添加属性 ref 和 属性名 mySon (随意),调用时使用 this.$ref.(属性名).(子组件方法);
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| <template> <view class=""> <son ref="mySon"></son> <button @click="fatherClick">父组件按钮</button> </view> </template> <script> import son from '@/components/son.vue' export default { components: { son }, methods: { fatherClick() { this.$refs.mySon.sonClick("father call son"); } } } </script>
|
2.子组件模板
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| <template> <view class=""> <text>子组件</text> </view> </template> <script> export default { name: 'son', methods: { sonClick(e) { console.log(e) } } } </script>
|