【问题标题】:How to use ref returned from Composition API in Options API?如何在 Options API 中使用从 Composition API 返回的 ref?
【发布时间】:2021-03-10 15:11:31
【问题描述】:

我正在运行 setup() 方法来导入仅适用于 Options API 的外部组件。因此,导入完成后,我需要使用 Options API data 配置组件。

如何在 Options API 的 data 区域中访问从 setup() 返回的 ref 值?这就是我的意思:

setup() {
    const IsBrowser = typeof window !== 'undefined';
    let EssentialsPlugin = ref(null);
    if (IsBrowser) {
      import('@ckeditor/ckeditor5-essentials/src/essentials').then(module => EssentialsPlugin.value = module);
    }

return {
 EssentialsPlugin
},

data() {
return { 
CKEditorConfig:  {
    plugins: [
      EssentialsPlugin   // Needs to be the EssentialsPlugin returned from setup()
]

如果我运行上面的代码,我会得到错误:Uncaught (in promise) ReferenceError: EssentialsPlugin is not defined

在这种情况下,CKEditor5 仅适用于 Vue 中的 Options API。它不能在 foreseeable future 的 Composition API 中配置。因此,如何使用来自 Composition API setup() 的 ref 值在 Options API 中配置它?

【问题讨论】:

    标签: javascript vue.js vuejs3 vue-composition-api


    【解决方案1】:

    如果您必须为 data 使用 Options API,那么使用生命周期挂钩似乎也是最明智的做法:

    data: () => ({
      isBrowser: typeof window !== 'undefined',
      CKEditorConfig: {
        plugins: []
      }
    }),
    created() {
      if (this.isBrowser) {
        import('@ckeditor/ckeditor5-essentials/src/essentials')
        .then(module => this.CKEditorConfig.plugins.push(module));
      }
    }
    

    【讨论】:

    • 我可以在 Options API 中从 setup() 访问 ref 吗?
    • 您可以将一个存储在单独的模块(或 Vuex)中,然后在生命周期钩子/方法中检索它
    • 好的,所以要确认它们不能在 Options API 中直接访问,但在模板中可以访问?
    • 我猜你可以这样说。只是 setup 没有合适的 this 来附加 ref,这就是选项 api 中访问选项的方式。
    猜你喜欢
    • 2020-11-26
    • 2020-11-11
    • 1970-01-01
    • 1970-01-01
    • 2020-04-10
    • 2022-01-25
    • 2020-05-13
    • 2021-04-03
    • 2023-02-17
    相关资源
    最近更新 更多