使用VueJs 2的全局数据 [英] Global data with VueJs 2

查看:134
本文介绍了使用VueJs 2的全局数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对VueJS相对较新,而且我不知道如何在全球范围内提供一些数据。我想保存API端点,用户数据以及从API中检索到的每个组件可以获取此数据的某些其他数据。

我知道我可以只用vanilla Javascript保存它但我想有一种方法可以用VueJS做到这一点。我或许可以使用事件总线系统来获取数据,但我不知道如何根据我的需要实现这个系统。

Im relatively new with VueJS, and I've got no clue about how to make some data globally available. I would like to save data like API endpoints, user data and some other data that is retrieved from the API somewhere where each component can get to this data.
I know I can just save this with just vanilla Javascript but I suppose there is a way to do this with VueJS. I may be able to use the event bus system to get the data but I don't know how I can implement this system to my needs.

如果我愿意的话有人可以帮我这个。

I would appreciate it if somebody can help me with this.

推荐答案

制作全球数据对象

const shared = {
    api: "http://localhost/myApi",
    mySharedMethod(){
        //do shared stuff
    }
}

如果你需要来公开它在你的Vue上,你可以。

If you need to expose it on your Vue, you can.

new Vue({
    data:{
        shared
    }
})

如果不这样做,你仍然可以在你的内部访问它Vues或组件,如果您已导入它或它们在同一页面上定义。

If you don't, you can still access it inside your Vues or components if you've imported it or they are defined on the same page.

它真的很简单。如果需要,您可以将共享作为属性传递,或者全局访问。

It's really as simple as that. You can pass shared as a property if you need to, or access it globally.

当您刚刚开始时,没有必要变得复杂即可。通常建议使用Vuex,但对于小型项目来说也常常过度。如果,稍后您发现需要它,那么添加它并不困难。它也适用于状态管理,听起来您真的想要访问一些全局数据。

When you're just starting out there is no real need to get complicated. Vuex is often recommended, but is also often overkill for small projects. If, later, you find you need it, it's not that hard to add it in. It's also really for state management and it sounds like you just really want access to some global data.

如果你想得到它,可以把它变成插件。

If you want to get fancy, make it a plugin.

const shared = {
  message: "my global message"
}

shared.install = function(){
  Object.defineProperty(Vue.prototype, '$myGlobalStuff', {
    get () { return shared }
  })
}

Vue.use(shared);

Vue.component("my-fancy-component",{
  template: "<div>My Fancy Stuff: {{$myGlobalStuff.message}}</div>"
})

new Vue({
  el: "#app"
})

现在,您创建的每个Vue和每个组件都可以访问它。这是一个示例

Now, every Vue you create and every component has access to it. Here is an example.

这篇关于使用VueJs 2的全局数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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