Laurence B.
Laurence B.

Reputation: 91

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 };
  },

Upvotes: 7

Views: 4542

Answers (2)

Michael
Michael

Reputation: 4393

As @Lagamura mentioned in the comments, this can be achieved with Vuetify 3 using useDisplay().

E.g.

const {mobile} = useDisplay();

console.log(mobile.value); 

Upvotes: 4

Yue JIN
Yue JIN

Reputation: 2146

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'

Upvotes: 9

Related Questions