Sunday, 20 December 2020

Cannot access Ionic component method from ref (Vue3)

I'm trying to access the closeSlidingItems method of the IonList component so that the sliding item is closed automatically once I click on a button which appears from behind after sliding this item to the right.

I tried to do it by putting a reference to IonList, then accessing it from the callback method for the click event on this button. However, I get an error:

Cannot read property 'closeSlidingItems' of undefined

This is the code in the root component:

<template>
  <ion-app>
    <ion-list ref="myIonList">
      <ion-item-sliding v-for="user in users" :key="user">
        <ion-item-options side="start">
          <ion-item-option v-on:click="favorite(user)" color="primary">
            <ion-icon slot="icon-only" :icon="heartOutline"></ion-icon>
          </ion-item-option>
        </ion-item-options>

        <ion-item :color="userState(user)">
          <ion-label slot="start"></ion-label>
          <ion-label slot="end"></ion-label>
        </ion-item>
      </ion-item-sliding>
    </ion-list>
  </ion-app>
</template>

<script>
import {
  IonApp,
  IonContent,
  IonList,
  IonLabel,
  IonItem,
  IonItemSliding,
  IonItemOptions,
  IonItemOption,
  IonIcon,
} from "@ionic/vue";
import { defineComponent } from "vue";
import { heartOutline } from "ionicons/icons";

export default defineComponent({
  name: "App",
  components: {
    IonApp,
    IonList,
    IonLabel,
    IonItem,
    IonItemSliding,
    IonItemOptions,
    IonItemOption,
    IonIcon,
  },
  data() {
    return {
      heartOutline,
      users: [
        {
          name: "John",
          age: 35,
          favorite: false,
        },
        {
          name: "Jane",
          age: 30,
          favorite: false,
        },
      ],
    };
  },
  methods: {
    favorite(user) {
      const favorite = user.favorite || false;
      user.favorite = !favorite;
      //console.log(this.$refs.myIonList);
      // This won't work despite I defined a reference to IonList and closeSlidingItems is a method of this component!
      this.$refs.myIonList.closeSlidingItems();
    },
    userState(user) {
      return user.favorite ? "success" : "";
    },
  },
});
</script>

And to try it by yourselves (try sliding one list item to the right and clicking on the heart icon):

https://codesandbox.io/s/ionic-vue-refs-2-msjj6?file=/src/App.vue

Could anyone help me find the issue and how to fix it, or work around it?



from Cannot access Ionic component method from ref (Vue3)

No comments:

Post a Comment