如何在设置函数中访问$vuetify示例

5cg8jx4n  于 2022-12-23  发布在  Vue.js
关注(0)|答案(2)|浏览(158)

有没有办法在setup函数中访问$vuetify(以及其他添加的全局变量)?有没有办法让可组合对象访问它?

...
  setup() {
    const { isDesktop } = $vuetify.breakpoints.mdAndUp; // <=== how to get $vuetify
    return { isDesktop };
  },
z9smfwbn

z9smfwbn1#

可组合以获取vuetify示例:

// 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
}

将其导入到组件中:

<!-- 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>

如果使用Vue〈= 2.6.14 + @vue/composition-api而不是Vue 2.7,请将'vue'替换为'@vue/composition-api'

p1iqtdky

p1iqtdky2#

正如@Lagamura在评论中提到的,这可以通过使用useDisplay()的Vuetify 3来实现。
例如

const display = useDisplay();

console.log(display.mobile.value);

相关问题