vue.js - 使用 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()
},
它按预期工作,但它似乎是一种访问插件方法的长期方法。这在架构上是不好的做法吗?
解决方案
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()
},
推荐阅读
- python - 修改字符串模板以使用其他变量作为修饰符
- php - 致命错误:不再支持 __autoload(),请在第 37 行的 C:\xampp\htdocs\jobportal\include\function.php 中使用 spl_autoload_register()
- .htaccess - 在 htaccess 中添加过期标头
- sql-server - 是否可以将 SSMS 中生成和显示的消息返回给调用应用程序(页面、控制台应用程序等)?
- python - 将元组和数据框连接在一起
- python - 如何将图像文件从 localhost React Native 应用程序发送到 localhost Flask API
- c++ - 相邻打印 2 个 for 循环
- java - 从 OpenPDF 获取溢出文本
- sas - Proc SQL 中的分区
- asp.net - .Net Core 3.1 产品动态多重过滤