Vue3-setup + this.$refs.* - how to deal with it

UI Components for Vue
Post Reply
cybay
Posts: 2
Joined: 03 Feb 2021, 19:00

03 Feb 2021, 19:06

I'd prefer to stick to one manner of code style, approach.
And I'd like to use new Vue3 composition API.
But a lot of components (at least menu, datatable) use this.$refs. to get access to needed stuff.
Inside 'setup' we don't have 'this' any more.
So how to deal with it?
Vue2 and its options API - is the only way out?

Unintended
Posts: 1
Joined: 07 Feb 2021, 16:57

07 Feb 2021, 17:02

Hey! I just ran into the same problem and figured it out. I am using Vue 3 with Comp.API and TS.

The thing I guess is that template refs are unified with regular refs so you simply create an empty ref in your code and bind that to the HTML element with ref="myRef". Then you can access it by using myRef.value.

My template

Code: Select all

<template>
  <div id="nav" class="small-container">
    <router-link to="/">Home</router-link> |
    <router-link to="/about">About</router-link>
    <i class="pi pi-user user-profile" @click="toggle"
      ><Menu ref="myRef" :model="items" :popup="true"
    /></i>
  </div>
  <router-view class="container" />
</template>

Code: Select all

<script lang="ts">
import { defineComponent, reactive, ref } from "vue";
import { user } from "@/helpers/useUsers";
import Menu from "primevue/menu";
export default defineComponent({
  components: { Menu },
  setup() {
    const items = reactive([
      {
        lable: "test",
        icon: "pi pi-refresh",
        command: () => {
          console.log(">==== TEST ====<");
        },
      },
    ]);
    const myRef = ref();
    const toggle = (event: any) => {
      myRef.value.toggle(event);
    };
    return { user, items, myRef, toggle };
  },
});
</script>
Template refs in Vue 3: https://v3.vuejs.org/guide/composition- ... plate-refs

Post Reply

Return to “PrimeVue”

  • Information
  • Who is online

    Users browsing this forum: No registered users and 7 guests