问题描述
我有一些来自 API-Server 的查询,它返回一个 json 对象,该对象在用户会话中是静态的,但不是永远静态的。 这是一个带有 Vue 路由器的单页浏览器。
我如何才能做到这一点: 可以访问所有组件中的 this.myGlobals(或类似的,例如 window.myGlobals),其中存储了我从 API-Server 预取的 json-data。
我的方法是通过 mixin 嵌入 help.js。
奇怪的是,我收到了数百个此查询的调用。起初我以为它只发生在前端并被chached,但请求实际上发送了数百次到服务器。我认为这是我的想法错误,或者是系统性错误。
我认为问题是,helper.js 不是静态存在于 vue 实例上
main.js:
import helpers from './helpers'
Vue.mixin(helpers)
helpers.js:
export default {
data: function () {
return {
globals: {},}
},methods: {
//some global helper funktions
},},mounted() {
let url1 = window.datahost + "/myDataToStore"
this.$http.get(url1).then(response => {
console.log("call")
this.globals.myData = response.data
});
}
}
登录控制台:
call
SomeOtherStuff
(31) call
SomeOtherStuff
(2) call
....
登录服务器:
call
call
call (pew pew)
我的下一个想法是学习 vuex,但由于它是一个简单的问题,我不确定我是否真的需要那个炸弹?
解决方法
您可以使用插件来实现这一点。
// my-plugin.js
export default {
install (Vue,options) {
// start fetching data right after install
let url1 = window.datahost + "/myDataToStore"
let myData
Vue.$http.get(url1).then(response => {
console.log("call")
myData = response.data
})
// inject via global mixin
Vue.mixin({
computed: {
myData () {
return myData
}
}
})
// or inject via instance property
Vue.prototype.$myData = myData
// or if you want to wait until myData is available
Vue.prototype.$myData = Vue.$http.get(url1)
.then(response => {
console.log("call")
myData = response.data
})
}
}
并使用它:
Vue.use(VueResource)
Vue.use(myPlugin)