-
-
Save douira/6d3f99fa4546adee470637467931ed19 to your computer and use it in GitHub Desktop.
import Vue from "vue" | |
//the properties of breakpoint that we want to mirror | |
const defaults = { | |
xs: true, | |
xsOnly: true, | |
sm: false, | |
smOnly: true, | |
smAndDown: true, | |
smAndUp: false, | |
md: false, | |
mdOnly: false, | |
mdAndDown: true, | |
mdAndUp: false, | |
lg: false, | |
lgOnly: false, | |
lgAndDown: true, | |
lgAndUp: false, | |
xl: false, | |
xlOnly: false | |
} | |
//create a property on the prototype of all instances that holds the breakpoint state | |
Vue.prototype.$breakpoint = new Vue({ | |
data: () => ({ ...defaults }) | |
}) | |
export default async function({ app }) { | |
//init mixins and the watchers if they don't exist yet | |
app.mixins = app.mixins || [] | |
app.watch = app.watch || {} | |
//create a watcher for each breakpoint | |
for (const prop in defaults) { | |
//the watcher sets the breakpoint prop to cause an update | |
app.watch[`$vuetify.breakpoint.${prop}`] = function(value) { | |
//update our mirrored value properly | |
this.$breakpoint[prop] = value | |
} | |
} | |
//add a mixin that does the client prop setting | |
app.mixins.push({ | |
//here is the magic, if we set the state with the correct value on client init it works | |
mounted() { | |
//for all props that we are processing | |
for (const prop in defaults) { | |
//set the initial value from vuetify | |
this.$breakpoint[prop] = this.$vuetify.breakpoint[prop] | |
} | |
} | |
}) | |
} |
Place this file in plugins/breakpoint.js
. Register it with Nuxt.js in nuxt.config.js
:
export default {
plugins: ["~/plugins/breakpoint"]
}
and then you can use $breakpoint
in your components with an expression like this.$breakpoint.smAndUp
.
Hi, is there anyway to use this in a switch statement?
switch (this.$breakpoint???)
at the moment I am creating a boolean when mounted.
if (this.mounted)
switch (this.$vuetify.breakpoint.name) {
case "xs":
}
No currently .name
does not exist. You can implement that yourself by adding more code to the generated watchers. There is probably helpful code in this file: https://github.com/vuetifyjs/vuetify/blob/088a5093ea6396d1ff12e0d62143f89572c667d6/packages/vuetify/src/services/breakpoint/index.ts
I recommend using a computed property for creating a boolean value that depends on a breakpoint state.
Hi, how does this get used in the app? can you give an example?