首页 > 解决方案 > 无法读取未定义的属性“$nuxt”

问题描述

我正在处理项目并在尝试从插件访问事件时nuxt.js遇到错误。Cannot read property '$nuxt' of undefined

~/plugins/myPlugin.js

import Vue from 'vue';

this.$nuxt.$on('emit-height', (payload) => {
  Vue.prototype.$bannerHeight = payload;
});

进口~/plugins/nuxt.config.js

plugins: [
  '~/plugins/get-main-banner-height.js',
]

this.$nuxt.$on如果我在任何组件中使用它但在上面提到的插件中不起作用,则可以使用。

在我的组件中,我正在发射高度。

methods: {
  getMainBannerHeight() {
    this.$nextTick(() => {
      this.$nuxt.$emit('emit-main-banner-height', this.bannerHeight);
    });
  },
}

所以,我的问题是“如何在插件中监听/捕获事件”?

标签: javascriptvue.jsnuxt.js

解决方案


您可以在 nuxt 插件的上下文中引用应用程序。文档https://nuxtjs.org/api/context/

import Vue from 'vue';

export default ({ app }) => {
  app.$on('emit-height', (payload) => {
    Vue.prototype.$bannerHeight = payload;
  });
}

推荐阅读