在VueJS中写入全局变量

Ton*_*man 2 javascript vue.js vuejs2

我正在使用:以VueJs 2为起点的全局数据,因为我只想读 /写一个变量。

我在现有代码中添加了@click事件以修改变量,但出现“未捕获的ReferenceError:未定义$ myGlobalStuff”。

谁能看到我在做什么错:

HTML:

 <div id="app2">
  {{$myGlobalStuff.message}}
  <my-fancy-component></my-fancy-component>
  <button @click="updateGlobal">Update Global</button>
</div>
Run Code Online (Sandbox Code Playgroud)

VueJS:

var shared = {消息:“我的全局消息”}

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
    }
  }
})
Run Code Online (Sandbox Code Playgroud)

如您所见,我向现有代码添加的内容很少,而且效果很好。

Any help on what I am overlooking would be appreciated.

Ber*_*ert 6

Well first, the error you are getting is because you do not reference $myGlobalStuff using this. Change to this

this.$myGlobalStuff.message = "Done it!"
Run Code Online (Sandbox Code Playgroud)

And you won't get the error anymore.

But I suspect it won't work the way you are expecting it to, in that, it won't be reactive. I think what you want is for the message to be updated on the page, and that is not really the intent of this code. The original point was just to supply some global values to each Vue or component.

To make it reactive we can add one change.

var shared = new Vue({data:{ message: "my global message" }})
Run Code Online (Sandbox Code Playgroud)

Once you do that, message will be a reactive value.

this.$myGlobalStuff.message = "Done it!"
Run Code Online (Sandbox Code Playgroud)
var shared = new Vue({data:{ message: "my global message" }})
Run Code Online (Sandbox Code Playgroud)

This is a very naive implementation of how Vuex works. The further you progress down this path, the more features of Vuex you end up implementing.