【问题标题】:Component custom options in Nuxt with Vue 3 composition APINuxt 中的组件自定义选项与 Vue 3 组合 API
【发布时间】:2020-12-20 19:03:27
【问题描述】:

在 Vue 2 中,您可以向组件定义对象添加自定义选项:

export default {
    title: 'TITLE',
    name: ...,
    components: { ... },
    render(h) { ... }
};

...这些选项将出现在组件的$options 属性(this.$options.title === 'TITLE')中。

此外,使用 Webpack,您可以添加代码来读取单个文件组件中的自定义块并将它们写入组件的 options 属性。

我正在 Nuxt 中使用module that implements the Vue 3 composition API for Nuxt 开发一个应用程序。这是一个全新的应用程序,所以我直接使用 Vue 3 和组合 API。但是,在引入自定义选项的问题上,我陷入了僵局。我已经搜索了setup 函数的context 参数和useContext() 提供的Nuxt 上下文的结果,但没有运气

如何使用 Vue 3 组合 API 模块从 Nuxt 中的组件获取自定义选项?

【问题讨论】:

  • 在哪种情况下需要自定义选项?
  • 读取自定义块并将其内容注入组件。

标签: nuxt.js vuejs3


【解决方案1】:

您可以使用getCurrentInstance() 访问$options。不确定这是否是“Vue3-proof”虽然?

此示例将在服务器端记录“测试”:

import { getCurrentInstance } from '@nuxtjs/composition-api'

export default {
  setup() {
    console.log(getCurrentInstance().$options.test) // Logs 'Test'
  },
  test: 'Test'
}

您也可以使用onMounted(或onBeforeMount)来访问客户端的值:

import { getCurrentInstance, onMounted } from '@nuxtjs/composition-api'

export default {
  setup() {
    /* Logs 'Test' on mounted */
    onMounted(() => { console.log(getCurrentInstance().$options.test) })
  },
  test: 'Test'
}

【讨论】:

猜你喜欢
  • 2021-09-15
  • 2021-11-27
  • 2021-11-14
  • 2021-09-18
  • 2022-11-16
  • 2020-12-20
  • 2021-07-31
  • 2018-10-25
  • 2022-01-18
相关资源
最近更新 更多