Obtain component instances by ref
Use ref to get a custom component instance and call its methods from a parent page or component. Requires mPaaS Mini Program 1.14.0 or later; use my.canIUse('component2') to check compatibility at runtime.
ref lets a page or parent component hold a direct reference to a child component instance so you can call that component's methods programmatically. The examples below show a counter component whose plus() method is called from its parent page.
When
refis bound tosaveRef, the framework callssaveRefautomatically as soon as the component is initialized.The
refparameter received bysaveRefis the custom component instance — the framework passes it in, so you do not construct it yourself.refworks in both page-to-component and parent-component-to-child-component scenarios.
Page JS
// /pages/index/index.js
Page({
plus() {
this.counter.plus();
},
// saveRef is called by the framework when the component mounts.
// ref is the component instance.
saveRef(ref) {
this.counter = ref;
},
})
this.counter holds the component instance. Calling this.counter.plus() from the page's plus() handler invokes the method directly on the component.
Page template
<!-- /pages/index/index.axml -->
<counter ref="saveRef" />
<button onTap="plus">+</button>
The ref="saveRef" attribute tells the framework to call saveRef on the parent Page object, passing the counter component instance as the argument.
Component JS
// /components/counter/index.js
Component({
data: {
counter: 0,
},
methods: {
plus() {
this.setData({ counter: this.data.counter + 1 })
},
},
})
Component template
<!-- /components/counter/index.axml -->
<view>{{counter}}</view>