像 Mixins 一样在 Vue js 中全局读取配置 [英] Read configuration globally in Vue js like Mixins

查看:20
本文介绍了像 Mixins 一样在 Vue js 中全局读取配置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个棘手的要求.我想通过调用 API 来读取配置(例如,id,api 等).然后我想全局保存这些值,以便我的所有 Vue 组件都可以读取它.

I have a tricky requirement. I want to read the configuration (ex, id, api etc) by making a API call. Then i want to save this values globally so that my all Vue components can read this.

我见过mixin.

但它看起来像是通用功能,我必须在我的组件中导入该 mixin.

如何只执行一次并直接为我的所有组件保存该值?我认为这个 example 看起来很适合我的需求,但我不能明白这是一个好方法吗?

How can i do this only once and save that values for all my components directly? I think this example is looks like suitable for my requinment but i am not able to understand that is this a good way?

推荐答案

Afaik,3 种方法可以随心所欲.

Afaik, 3 ways to do it what you want.

  • 混合
  • 供应商
  • Vuex

我个人更喜欢提供者,您只需要在需要时注入即可.它可能比 mixin 解决方案更轻.

I personally prefer provider, you just need to inject when you need it. Its probably lighter than mixin solution.

这是快速预览.

export default {
  name: 'RootComponent',
  provide () {
    let provider = {}
    Object.defineProperty(provider, 'appSettings', {
      iteratable: true,
      get: () => this.appSettings
    })
    return provider
  },
  data () {
    return {
      appSettings: {}
    }
  },
  mounted () {
    this.yourApiCall().then((result) => {
      this.$set(this.$data, 'appSettings', result)
    })
  }
}

export default {
  name: 'SubComponent',
  inject: ['appSettings'],
  mounted () {
    console.log(this.appSettings)
  }
}

这篇关于像 Mixins 一样在 Vue js 中全局读取配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆