vue.js - 如何在 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: () => { /* ... */ } }
]
})
}
解决方案
您可以为这样的通知定义一个实用程序:
// 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>
推荐阅读
- javascript - 为什么我的硬币找零功能包含在记忆缓存中时不起作用?
- javascript - React 生产应用程序中是否需要 .map 文件?
- .net - 如何将 .Net UWP C# 项目添加到具有 Windows 窗体 .net 项目的解决方案中
- java - 自定义方法spring mongo存储库不返回数据
- jquery - jQuery:有时随机失败
- node.js - Maximum call stack exceeded running npm install
- amazon-web-services - Does AWS Console uses Amplify library for Cognito Auth?
- python - 如何在 Eclipse 中修复未解析的导入 PyDev
- django - 列出用户,包含有关这些用户的大量数据。如何为每个用户将一对多表中的最后一条记录添加到该列表中?
- mysql - MySQL multi-table join with nulls