Use Ref to Get Component Instance
The custom component supports using ref to get custom component instance. Use my.canIUse('component2') for compatibility handling.
Note:
ref can be used as well for parent component to get children component instance.
Sample Code:
copy
// /pages/index/index.js
Page({
plus() {
this.counter.plus();
},
saveRef(ref) {
this.counter = ref;
},
})
copy
<!-- /pages/index/index.axml -->
<counter ref="saveRef" />
<button onTap="plus">+</button>
Note: After ref is bound to saveRef, the saveRef method is triggered on component initialization.
copy
// /components/counter/index.js
Component({
data: {
counter: 0,
},
methods: {
plus() {
this.setData({ counter: this.data.counter + 1 })
},
},
})
copy
<!-- /components/counter/index.axml -->
<view>{{counter}}</view>