在 vue3 插件中访问$vuetify

Access $vuetify in vue3 plugin

提问人:R.Duteil 提问时间:11/17/2023 更新时间:11/17/2023 访问量:25

问:

我正在尝试制作一个 vue3 插件,该插件需要访问$vuetify才能进行一些与主题相关的工作。 我尝试了几件事,但无法成功。

我的插件看起来像这样

export const ColorPlugin: Plugin = {
    install: (app) => {
        app.config.globalProperties.$color = function(this: InstanceType<DefineComponent>, key: string): string {
            let color = (this.$vuetify as any).theme.current.colors[key];

            // Do some work on the color

            return color;
        }
    }
}

我像这样导入插件

export function registerPlugins (app: App) {
  loadFonts();
  app.use(vuetify).use(ColorPlugin);
}

...

const app = createApp(App);
registerPlugins(app);
app.mount('#app');

我把一些组件定义为

<template>
  <div :style="wrapperStyle">
    <v-icon v-if="icon" :color="$color(color)">
      {{ icon }}
    </v-icon>
    <span v-if="label">
      {{ label }}
    </span>
  </div>
</template>

<script lang="ts">
import { defineComponent, getCurrentInstance, PropType } from "vue";

export default defineComponent({
  name: "FSLabelWithIcon",
  props: {
    icon: {
      type: String,
      required: false,
      default: null
    },
    label: {
      type: String,
      required: false,
      default: null
    },
    iconColor: {
      type: String,
      required: false,
      default: "primary"
    },
    backgroundColor: {
      type: String,
      required: false,
      default: "secondary"
    },
  },
  setup(props) {
    // only way I found to use the $color function declared in my plugin
    const globalProperties = getCurrentInstance().appContext.config.globalProperties;


    const contentStyle = {
      display: "flex",
      alignItems: "center",
      gap: "8px",
      backgroundColor: globalProperties.$color(props.backgroundColor)
    };

    return {
      icon: props.icon,
      label: props.label,
      color: props.iconColor,
      contentStyle
    };
  }
})
</script>

现在我面临的问题是模板中的$color调用工作正常,但设置中的调用会引发错误,因为 this.$vuetify 未定义。

如何从模板和设置在我的插件中访问 this.$vuetify?

vuejs3 vuetify.js

评论


答:

1赞 Moritz Ringler 11/17/2023 #1

在 Vuetify 3 中,全局对象被丢弃,取而代之的是可组合项。对于与主题相关的数据,请使用 useTheme 可组合项:$vuetify

useTheme().current.colors[key]

下面是一个游乐场示例

评论

0赞 R.Duteil 11/17/2023
似乎useTheme()只能在设置过程中使用,甚至不能在设置返回的函数中使用。因此,我无法使用我的 $color 函数动态计算颜色的某些变化。有没有办法从组件的模板中使用useTheme()调用函数?
0赞 Moritz Ringler 11/17/2023
通常,您将在安装过程中调用并存储返回的值,您可以在模板中使用该值useTheme