All Products
Search
Document Center

Obtain component instances by ref

Last Updated: Feb 04, 2021

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.

 
  1. // /pages/index/index.js
  2. Page({
  3. plus() {
  4. this.counter.plus();
  5. },
  6. // The ref parameter of the saveRef method is the custom component instance. The parameter is passed to saveRef by the framework during operation.
  7. saveRef(ref) {
  8. // Stores the custom component instance for future call.
  9. this.counter = ref;
  10. },
  11. })
 
  1. <!-- /pages/index/index.axml -->
  2. <counter ref="saveRef" />
  3. <button onTap="plus">+</button>
Note:
  • After saveRef is bound using ref, the saveRef method will be triggered when the component is initialized.
  • The ref parameter of the saveRef method is the custom component instance. The parameter is passed to saveRef by the framework.
  • ref can be used for the parent component to obtain the instance of the child component.
 
  1. // /components/counter/index.js
  2. Component({
  3. data: {
  4. counter: 0,
  5. },
  6. methods: {
  7. plus() {
  8. this.setData({ counter: this.data.counter + 1 })
  9. },
  10. },
  11. })
 
  1. <!-- /components/counter/index.axml -->
  2. <view>{{counter}}</view>