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

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

问题描述

我有一个棘手的要求.我想通过进行API调用来读取配置(例如,ex,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导入我的组件中.

我该怎么做一次并直接保存所有组件的值? 我认为这个示例看起来很适合我,但我无法知道这是个好方法吗?

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.

  • Mixin
  • 提供商
  • Vuex

我个人更喜欢提供者,您只需要在需要时注入即可.它可能比混合溶液更轻.

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天全站免登陆