In 1.14.0
and later versions, ref
can be used to obtain custom component instances, and my.canIUse('component2')
can be used for compatibility.
// /pages/index/index.js
Page({
plus() {
this.counter.plus();
},
// The ref parameter of the saveRef method is the custom component instance. The parameter is passed to saveRef by the framework during operation.
saveRef(ref) {
// Stores the custom component instance for future call.
this.counter = ref;
},
})
<!-- /pages/index/index.axml -->
<counter ref="saveRef" />
<button onTap="plus">+</button>
Note:
- After
saveRef
is bound usingref
, thesaveRef
method will be triggered when the component is initialized. - The
ref
parameter of thesaveRef
method is the custom component instance. The parameter is passed tosaveRef
by the framework. ref
can be used for the parent component to obtain the instance of the child component.
// /components/counter/index.js
Component({
data: {
counter: 0,
},
methods: {
plus() {
this.setData({ counter: this.data.counter + 1 })
},
},
})
<!-- /components/counter/index.axml -->
<view>{{counter}}</view>