javascript - Vue SPA - 从任何组件调用方法
问题描述
我正在开发可以从任何组件调用的通知功能。这是一个简单的Vuetify
v-snackbar
.
在App.vue
<router-view :key="$route.fullPath"></router-view>
<v-snackbar :value="showNotification" :multi-line="false">{{
notificationText
}}
</v-snackbar>
和方法
methods:{
notify(text){
this.notificationText = text
this.showNotification = true
}
}
这显然在内部工作,App.vue
但我想notify
从任何组件调用。我怎样才能做到这一点?我用router
解决方案
在 main.js 添加全局属性:
import Vue from 'vue'
Vue.prototype.$notificationText = ''
Vue.prototype.$showNotification = false
....
应用程序.vue
<router-view :key="$route.fullPath"></router-view>
<v-snackbar :value="$showNotification" :multi-line="false">{{
$notificationText
}}
</v-snackbar>
然后任何组件都可以:
methods:{
notify(text){
this.$notificationText = text
this.$showNotification = true
}
}
推荐阅读
- python - 将 numpy 数组转换为 dask 数据框列?
- html - 如何通过 id 从 html 字符串中获取元素
- php - 为什么 $_POST 在 codeigniter 中是空的?
- java - 尝试查找菜单项时,应用程序在屏幕旋转时崩溃
- ruby - ArgumentError:缺少必需的选项:key
- unity3d - SetActive(true) 在协程中不起作用
- r - 基于 R 中具有 p 值的多列值创建相关矩阵
- angular - 在 Angular 中使用 IdentityServer4 + oidc-client-js 在空闲时注销用户
- rust - 相当于#[cfg(test)] 的基准测试?
- python - matplotlib 的日期时间问题