首页 > 解决方案 > 在 VusJS 中访问子组件内的插槽函数

问题描述

我正在尝试使用tiptap。实际上它有效,但我想做的是从editor组件外部访问“isActive”插槽,我不知道该怎么做。

这是一个代码框示例:https ://codesandbox.io/s/v07xnxo807?file=/src/App.vue

您会看到 Editor 组件是从 App.vue 调用的。编辑器组件中的按钮根据“isActive”插槽功能激活。我想要访问此插槽以获取例如isActive.bold()来自 App.vue 的值,以便更新您可以在 Vuetify 上找到的“多个按钮”的模型:https ://vuetifyjs.com/fr- FR/组件/按钮组/

例如,这是我可以拥有的:

<editor-menu-bar :editor="editor" v-slot="{ commands, isActive }">
  <v-btn-toggle
    v-model="toggle_multiple"
    dense
    background-color="primary"
    dark
    multiple
    class="my-2"
  >
    <v-btn :color="isActive.bold()?'red':'green'" @click="commands.bold">
      <v-icon>mdi-format-bold</v-icon>
    </v-btn>
    <v-btn @click="commands.italic">
      <v-icon>mdi-format-italic</v-icon>
    </v-btn>
    <v-btn @click="commands.strike">
      <v-icon>mdi-format-strikethrough</v-icon>
    </v-btn>
    <v-btn @click="commands.underline">
      <v-icon>mdi-format-underline</v-icon>
    </v-btn>
    <v-btn @click="commands.blockquote">
      <v-icon>mdi-format-quote-open</v-icon>
    </v-btn>
  </v-btn-toggle>
</editor-menu-bar>

并且toggle_multiple 将根据不同的“isActive”函数值来计算。

我已经尝试过:

computed: {
  toggle_multiple: function () {
    let t = []
    if (editor)  {console.log("Bold: "+editor.isActive.bold())}
    return t
  }
},

但我收到此错误:error 'editor' is not defined

我愿意接受任何建议。提前致谢。

标签: vue.jstiptap

解决方案


属性isActive存储在 tiptap 实例中(在您的情况下是this.editor):

在 HTML 中:

<div>{{editor.isActive.bold()}}</div>

在 JS 中:

<div>{{toggle_multiple}}</div>
computed: {
  toggle_multiple () {
    // Keep in mind, other properties like ".isActive.heading()" will be undefined
    // until you import the extension for it.
    // So the function "heading" below exists only if you're using that extension
    // console.log(this.editor.isActive.heading({ level: 2 })
    return this.editor.isActive.bold()
  }
}

推荐阅读