问题描述
在Vue 2中,您可以向组件定义对象添加自定义选项:
export default {
title: 'TITLE',name: ...,components: { ... },render(h) { ... }
};
...,这些选项将显示在组件的$options
属性(this.$options.title === 'TITLE'
)中。
此外,使用Webpack,您可以添加代码以读取单个文件组件中的自定义块并将其写入到该组件的options
属性中。
我正在使用module that implements the Vue 3 composition API for Nuxt在Nuxt中开发一个应用程序。这是一个全新的应用程序,因此我将直接介绍Vue 3和composition API。但是,在引入自定义选项方面,我一直处于僵局。我已经搜索了context
函数的setup
参数和useContext()提供的Nuxt上下文的结果,都没有运气
如何使用Vue 3 composition API模块从Nuxt的组件中获取自定义选项?
解决方法
您可以使用getCurrentInstance()
来访问$options
。不确定though
此示例将在服务器端记录“测试”:
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'
}