我正在使用:Global data with VueJs 2作为我的起点,因为我只想读/写一个变量。
我已将 @click 事件添加到现有代码以修改变量,但我收到“未捕获的 ReferenceError:$myGlobalStuff 未定义”。
谁能看出我做错了什么:
HTML:
<div id="app2">
{{$myGlobalStuff.message}}
<my-fancy-component></my-fancy-component>
<button @click="updateGlobal">Update Global</button>
</div>
VueJS:
var 共享 = { 消息:“我的全局消息”
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: "#app2",
mounted(){
console.log(this.$store)
},
methods: {
updateGlobal: function() {
$myGlobalStuff.message = "Done it!"
return
}
}
})
如您所见,我在现有代码中添加的内容很少,效果很好。
对于我忽略的内容,我们将不胜感激。
最佳答案
首先,您遇到的错误是因为您没有使用 this
引用 $myGlobalStuff
。改成这个
this.$myGlobalStuff.message = "Done it!"
你不会再收到错误了。
但我怀疑它不会像您期望的那样工作,因为它不会是被动的。我认为您想要的是在页面上更新消息,而这并不是这段代码的真正意图。最初的目的只是为每个 Vue 或组件提供一些全局值。
要使其响应,我们可以添加一项更改。
var shared = new Vue({data:{ message: "my global message" }})
一旦你这样做了,message
将是一个 react 值。
console.clear()
var shared = new Vue({data:{ 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: "#app2",
mounted(){
console.log(this.$store)
},
methods: {
updateGlobal: function() {
this.$myGlobalStuff.message = "Done it!"
return
}
}
})
<script src="https://unpkg.com/vue@2.2.6/dist/vue.js"></script>
<div id="app2">
{{$myGlobalStuff.message}}
<my-fancy-component></my-fancy-component>
<button @click="updateGlobal">Update Global</button>
</div>
这是 Vuex 工作方式的非常天真的实现。沿着这条路走得越远,最终实现的 Vuex 功能就越多。
关于javascript - 在 VueJS 中写入全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45111200/