首页 > 解决方案 > 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

标签: javascriptvue.jsvue-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
 }
}

推荐阅读