Vue封装vue-notification:简化通知调用方式遇阻求助
我来帮你搞定这个问题!你想要简化vue-notification的调用,让它只传消息就能触发,核心问题出在你当前的notifications.js里用了getter来定义$notify——getter是没法接收参数的,所以传的message根本拿不到。咱们来修改一下实现:
解决方案
首先,修改你的notifications.js,把$notify定义成一个可接收参数的函数,同时保留全局调用的能力,并且预设好你需要的默认配置:
import Vue from 'vue' import Notifications from 'vue-notification' // 先安装vue-notification插件 Vue.use(Notifications) export default function install(Vue) { // 封装全局调用的notify,预设默认参数 const baseNotify = (message, options = {}) => { return Vue.notify({ group: 'panel', type: 'success', duration: 5000, text: message, ...options // 允许传入额外参数覆盖默认值 }) } // 给Vue原型挂载$notify,供组件内调用 Vue.prototype.$notify = baseNotify // 同时保留全局调用的方式 Vue.notify = baseNotify }
然后你的main.js不需要改动,保持原来的引入和使用方式就行:
import Vue from 'vue' import App from './App.vue' import notifications from './support/notifications' Vue.use(notifications) new Vue({ render: h => h(App) }).$mount('#app')
现在你就能按想要的方式调用了:
- 在Vue组件内:
this.$notify('操作成功!') // 如果需要覆盖默认配置,还可以传第二个参数 this.$notify('操作警告', { type: 'warn', duration: 3000 })
- 在.js文件内:
import Vue from 'vue' Vue.notify('数据已更新!') // 同样支持自定义参数 Vue.notify('错误提示', { type: 'error', group: 'other' })
为什么原来的代码没生效?
你之前用Object.defineProperty的get方法来定义$notify,但getter函数是不能接收参数的——当你调用this.$notify('message')时,这个message参数根本不会被getter捕获到。所以我们需要把$notify定义成一个普通的函数,这样才能接收传入的消息内容和自定义配置。
内容的提问来源于stack exchange,提问作者Caio Kawasaki
相关产品推荐
相关产品推荐

