首页 > 解决方案 > 使用 fetch() 在布局中访问 Vue Nuxt 插件

问题描述

想问我这样做是否正确,感觉很笨拙。我正在访问 Nuxt 布局组件中的插件。我想通过新的fetch()api 在布局中动态生成内容。

async fetch() {
  this.notifications = await this.$root.context.app.contentfulClient.getNotifications()
  this.treatments = await this.$root.context.app.contentfulClient.getTreatments()
},

它按预期工作,但它似乎是一种访问插件方法的长期方法。这在架构上是不好的做法吗?

标签: vue.jsfetchnuxt.js

解决方案


Nuxt 插件通常会向 Nuxt 上下文添加属性,使它们可以从组件中使用,this而无需像您正在做的那样显式地深入到上下文中。

假设你的插件像这样注入 contentfulClient

// ~/plugins/contentfulClient.js
export default ({ app }, inject) => {
  inject('contentfulClient', {
    async getNotifications() {/*...*/},
    async getTreatments() {/*...*/},
  })
}

然后你的组件可以像这样使用它:

async fetch() {
  this.notifications = await this.$contentfulClient.getNotifications()
  this.treatments = await this.$contentfulClient.getTreatments()
},

推荐阅读