简体   繁体   English

在 nuxt.js 中创建我自己的全局变量(使用 vuetify)

[英]create my own global variable in nuxt.js (with vuetify)

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.我正在使用 nuxt 开发一个应用程序,我厌倦了每次都必须使用 this.$Vuetify.breakpoint.name == 'xs' 在页面中编写 if 语句来提高响应能力。 So I would like to create my own variable and call this long variable.here is my code↓所以我想创建我自己的变量并调用这个长变量。这是我的代码↓

(mynuxtapp/plugins/createCustomVar.js) (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.我已经设置了 nuxtconfig 来运行插件。 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.显然我无法使用“$”访问 vuetify,即使我可以在页面中进行。

What should I do?我应该怎么办? and Are there any easier ways or best practices?有没有更简单的方法或最佳实践? Thank you for reading the question at the end!感谢您阅读最后的问题!

How about to start with you simply log out the context object and see what you have.如何从您简单地注销上下文对象并查看您拥有的内容开始。 I think you'll probably find that the Vuetify object is lying somewhere else.我想您可能会发现 Vuetify 对象位于其他地方。

export default (context, inject) => {
  console.log('context:', context)
}

Docs for setting plugins can be found here可以在此处找到用于设置插件的文档

The $vuetify property exists on the Nuxt context, not the Vue prototype. $vuetify属性存在于 Nuxt 上下文中,而不是 Vue 原型中。

Each module under plugins/ should return a function that receives the Nuxt context as the first argument. plugins/下的每个模块都应该返回一个函数,该函数接收 Nuxt 上下文作为第一个参数。 That context contains the $vuetify object setup by the @nuxtjs/vuetify plugin.该上下文包含由@nuxtjs/vuetify插件设置的$vuetify对象。

The second argument of the Plugin API is inject , which allows you to inject globals into the Nuxt context . Plugin API 的第二个参数是inject ,它允许您将全局变量注入 Nuxt 上下文

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

demo 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM