我正在尝试在Vue中创建一个全局变量,以便可以在整个应用程序中读取和更新。我决定使用原型方法,但是由于某种原因,变量被更新(console.log更改),但是前端()未被更新。有人可以向我解释为什么这样做以及如何解决这个“全局变量”问题。
main.js
:
Vue.prototype.$something = 'Hi there!';
// I tried this but it gives the same result
// Vue.prototype.$something = { text: 'Hi there!' };
component1.vue
:
<label>{{$something}}</label>
component2.vue
:
<label>{{$something}}</label>
<button v-on:click="changeThat()">Change</button>
...
changeThat() {
console.log(this.$something); // 'Hi there!'
this.$something = "Good bye!";
console.log(this.$something); // 'Good bye!'
}
我想在更改<label>
时更新两个this.$something
。
您这样使用Vue.observable:
Vue.prototype.$globalData = Vue.observable({
label: 'test'
});
在应用程序的任何组件中,您都可以像这样使用它:
{{ $globalData.label }}
如果您将label
更改为以下位置:
this.$globalData.label = 'new test';
它将反映在所有组件中。