The question is published on by Tutorial Guruji team.
I’m developing an app with nuxt and I’m tired of having to write an if statement in pages using this.$Vuetify.breakpoint.name == ‘xs’ for responsiveness every time. So I would like to create my own variable and call this long variable.here is my code↓
(mynuxtapp/plugins/createCustomVar.js)
import Vue from "vue"; Vue.prototype.$bp = Vue.prototype.$vuetify.breakpoint.name; console.log(Vue.prototype.$bp);
I have already set nuxtconfig to run the plugin. But it returns an error: TypeError: Cannot read property’breakpoint’ of undefined. Apparently I can’t access vuetify using “$”, even though I can do it in pages.
What should I do? and Are there any easier ways or best practices? Thank you for reading the question at the end!
Answer
The $vuetify
property exists on the Nuxt context, not the Vue prototype.
Each module under plugins/
should return a function that receives the Nuxt context as the first argument. That context contains the $vuetify
object setup by the @nuxtjs/vuetify
plugin.
The second argument of the Plugin API is inject
, which allows you to inject globals into the Nuxt context.
So your plugin should look similar to this:
// ~/plugins/myGlobals.js export default ({ $vuetify }, inject) => { // inject makes `$bp` available in context (the `$` prefix is automatically prefixed) inject('bp', $vuetify.breakpoint.name) }