【问题标题】:Make a variable available to all Vue components without explicitly passing it by props?让所有 Vue 组件都可以使用一个变量,而无需通过 props 显式传递它?
【发布时间】:2020-03-25 15:38:39
【问题描述】:

我有一个问题,所以在 react 中,我们有 react 消费者和提供者,可以让变量传递到我想要的任何地方。 Vue有类似的东西吗? 我需要将我的 Firebase 类传递给几乎每个组件,所以通过 props 传递它是个坏主意。

【问题讨论】:

标签: vue.js vue-props


【解决方案1】:

您可以为任何模块(即本例中的 firebase)创建包装插件。

/plugins/firebase-wrapper.js

import firebase from 'firebase'

const FirebaseWrapper = {
  install (Vue) {
    // INSTALL
    if (this.installed) return
    this.installed = true

    // CONFIG
    const config = {
     apiKey: "",
     authDomain: "",
     databaseURL: "",
     projectId: "",
     storageBucket: "",
     messagingSenderId: ""
    }

    // INIT
    firebase.initializeApp(config)

    Vue.prototype.$firebase = firebase
    Vue.firebase = firebase
  }
}

export default FirebaseWrapper

main.js

import FirebaseWrapper from "./plugins/firebase-wrapper.js"
Vue.use(FirebaseWrapper)

从 .vue 文件访问 firebase API,如下所示

let currentUser = await this.$firebase.auth().currentUser

或者

import Vue from 'vue'
let currentUser = await Vue.firebase.auth().currentUser

vuefire(npm 模块)可能会为您做同样的事情,即。将创建一个包装器插件并使 firebase API 全球可用,因此您不必编写自己的自定义插件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-30
    • 2020-02-09
    • 2021-12-09
    • 2021-04-19
    • 2011-02-27
    • 2019-02-02
    • 2018-04-23
    • 1970-01-01
    相关资源
    最近更新 更多