在 nuxt.js 中创建我自己的全局变量(使用 vuetify)
create my own global variable in nuxt.js (with vuetify)
我正在使用 nuxt 开发一个应用程序,我厌倦了每次都必须在页面中使用 this.$Vuetify.breakpoint.name == 'xs' 来编写 if 语句以获得响应。所以我想创建自己的变量并调用这个 long variable.here 是我的代码↓
(mynuxtapp/plugins/createCustomVar.js)
import Vue from "vue";
Vue.prototype.$bp = Vue.prototype.$vuetify.breakpoint.name;
console.log(Vue.prototype.$bp);
我已经将 nuxtconfig 设置为 运行 插件。
但它 returns 一个错误:
类型错误:无法读取未定义的 属性'断点'。
显然我无法使用“$”访问 vuetify,即使我可以在页面中进行访问。
我该怎么办?有没有更简单的方法或最佳实践?
感谢您阅读最后的问题!
如何开始,您只需注销上下文对象并查看您有什么。我想您可能会发现 Vuetify 对象位于其他地方。
export default (context, inject) => {
console.log('context:', context)
}
可以找到设置插件的文档here
$vuetify
属性 存在于 Nuxt 上下文中,而不是 Vue 原型。
plugins/
下的每个模块都应该 return 一个接收 Nuxt 上下文作为第一个参数的函数。该上下文包含由 @nuxtjs/vuetify
插件设置的 $vuetify
对象。
插件 API 的第二个参数是 inject
,它允许您 inject globals into the Nuxt context.
所以你的插件应该看起来像这样:
// ~/plugins/myGlobals.js
export default ({ $vuetify }, inject) => {
// inject makes `$bp` available in context (the `$` prefix is automatically prefixed)
inject('bp', $vuetify.breakpoint.name)
}
我正在使用 nuxt 开发一个应用程序,我厌倦了每次都必须在页面中使用 this.$Vuetify.breakpoint.name == 'xs' 来编写 if 语句以获得响应。所以我想创建自己的变量并调用这个 long variable.here 是我的代码↓
(mynuxtapp/plugins/createCustomVar.js)
import Vue from "vue";
Vue.prototype.$bp = Vue.prototype.$vuetify.breakpoint.name;
console.log(Vue.prototype.$bp);
我已经将 nuxtconfig 设置为 运行 插件。 但它 returns 一个错误: 类型错误:无法读取未定义的 属性'断点'。 显然我无法使用“$”访问 vuetify,即使我可以在页面中进行访问。
我该怎么办?有没有更简单的方法或最佳实践? 感谢您阅读最后的问题!
如何开始,您只需注销上下文对象并查看您有什么。我想您可能会发现 Vuetify 对象位于其他地方。
export default (context, inject) => {
console.log('context:', context)
}
可以找到设置插件的文档here
$vuetify
属性 存在于 Nuxt 上下文中,而不是 Vue 原型。
plugins/
下的每个模块都应该 return 一个接收 Nuxt 上下文作为第一个参数的函数。该上下文包含由 @nuxtjs/vuetify
插件设置的 $vuetify
对象。
插件 API 的第二个参数是 inject
,它允许您 inject globals into the Nuxt context.
所以你的插件应该看起来像这样:
// ~/plugins/myGlobals.js
export default ({ $vuetify }, inject) => {
// inject makes `$bp` available in context (the `$` prefix is automatically prefixed)
inject('bp', $vuetify.breakpoint.name)
}