首页 > 解决方案 > 如何在 Quasar Vue V2 框架中设置一些全局函数/mixin

问题描述

我将 Quasar Framework V2 用于 SPA,我需要创建一个类,我可以在其中声明应用程序上的所有共享函数/方法以减少代码编写。

例如,要显示来自 Notify 插件的警报,您必须使用以下代码:

$q.notify({
          message: 'Error',
          color: 'primary',
          actions: [
            { label: 'Dismiss', color: 'white', handler: () => { /* ... */ } }
          ]
        })

在我希望调用该通知的每个事件中都写这个太长了。但我不知道在 Quasar 上执行此操作的正确方法。 我尝试使用引导文件但失败了

我只想notifyError()从全局类/mixin/boot 或其他任何地方调用。像这样的东西:

const notifyError = () => {

$q.notify({
          message: 'Jim just pinged you.',
          color: 'primary',
          avatar: 'https://cdn.quasar.dev/img/boy-avatar.png',
          actions: [
            { label: 'Reply', color: 'yellow', handler: () => { /* ... */ } },
            { label: 'Dismiss', color: 'white', handler: () => { /* ... */ } }
          ]
        })

}

标签: vue.jsvuejs3quasar-framework

解决方案


您可以为这样的通知定义一个实用程序:

// If you're not using Quasar CLI, you probably have a quasar.js file that you'll need to import inside main.js
import Vue from 'vue';
import { Quasar, Notify } from 'quasar';

Vue.use(Quasar, {
  // You can configure here how notify works
  config: {
    notify: {
    position: 'top-right',
    timeout: 2000,
  },
  // You need to import the plugin
  plugins: {
    Notify,
  },
});

// If you're using Quasar CLI, you need to add the Notify plugin in quasar.conf.js
module.exports = function () {
  return {
    framework: {
      plugins: [
        'Notify',
      ],
    },
  };
};

// util/notify.js
import { Notify } from 'quasar';

const error = (message) => {
  Notify.create({
    message,
    color: 'primary',
    actions: [
      { label: 'Dismiss', color: 'white', handler: () => { /* ... */ } },
    ],
  });
};

const primary = (message) => {
  Notify.create({
    message,
    color: 'primary',
    avatar: 'https://cdn.quasar.dev/img/boy-avatar.png',
    actions: [
      { label: 'Reply', color: 'yellow', handler: () => { /* ... */ } },
      { label: 'Dismiss', color: 'white', handler: () => { /* ... */ } },
    ],
  });
};

export default {
  error,
  primary,
};

// Home.vue
<template>
  ...
</template>

<script>
import notify from '@/notify';

export default {
  name: 'Home',
  async created() {
    notify.primary('message');
  },
};
</script>

推荐阅读