Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access $vuetify instance in setup function

Is there a way to get access to $vuetify (and any other added global) in the setup function? Is there a way for composables to access it?

  ...
  setup() {
    const { isDesktop } = $vuetify.breakpoints.mdAndUp; // <=== how to get $vuetify
    return { isDesktop };
  },
like image 553
Laurence B. Avatar asked Jul 21 '26 06:07

Laurence B.


1 Answers

Composable to get vuetify instance:

// useVuetify.ts
import { getCurrentInstance } from 'vue'

export function useVuetify() {
  const instance = getCurrentInstance()
  if (!instance) {
    throw new Error(`useVuetify should be called in setup().`)
  }
  return instance.proxy.$vuetify
}

Import it in your component:

<!-- MyComponent.vue -->
<script lang="ts">
import { useVuetify } from './useVuetify'
import { computed } from 'vue'

/*...*/
  setup() {
    const vuetify = useVuetify()
    const isDesktop = computed(()=>vuetify.breakpoints.mdAndUp)
    return { isDesktop }
  },
/*...*/
</script>

If you are using Vue <= 2.6.14 + @vue/composition-api instead of Vue 2.7, replace 'vue' with '@vue/composition-api'

like image 52
Yue JIN Avatar answered Jul 23 '26 04:07

Yue JIN



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!