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

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

问题描述

我对 VueJS 比较陌生,我不知道如何使某些数据全局可用.我想将 API 端点、用户数据和其他一些从 API 检索的数据保存在每个组件可以访问这些数据的地方.
我知道我可以只用普通的 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
    }
})

如果不这样做,如果您已经导入它或者它们在同一页面上定义,您仍然可以在您的 Vue 或组件中访问它.

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.

其实就是这么简单.如果需要,您可以将 shared 作为属性传递,或全局访问它.

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