2017-07-14 59 views
1

我正在使用:Global data with VueJs 2作爲我的出發點,因爲我只想讀取一個變量。在VueJS中寫入全局變量

我已經添加了一個@click事件到現有的代碼來修改變量,但我得到了「Uncaught 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 
    } 
    } 
}) 

正如你所看到的我添加很少到現有的代碼,並且運行良好。

任何對我所忽略的幫助將不勝感激。

回答

1

首先,你得到的錯誤是因爲你沒有使用this引用$myGlobalStuff。更改爲此

this.$myGlobalStuff.message = "Done it!" 

而且您不會再出現錯誤。

但我懷疑它不會按照你期待的方式工作,因爲它不會被動。我認爲你想要的是在頁面上更新消息,這不是這個代碼的意圖。最初的觀點是爲每個Vue或組件提供一些全局值。

爲了使它反應我們可以添加一個更改。

var shared = new Vue({data:{ message: "my global message" }}) 

一旦你這樣做,message將是一個被動的值。

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/[email protected]/dist/vue.js"></script> 
 
<div id="app2"> 
 
    {{$myGlobalStuff.message}} 
 
    <my-fancy-component></my-fancy-component> 
 
    <button @click="updateGlobal">Update Global</button> 
 
</div>

這是一個非常天真實施Vuex是如何工作的。沿着這條路走得越遠,Vuex最終實現的功能就越多。

+0

感謝伯特,你一定哭了,看到你的代碼,很容易搞砸了。好的理解,但變量會改變,我真的不需要被動,只是一個全球性的商店。我只是用事件來證明我發生的變化。 –

+0

@TonySherman它確實更新了變量,但變量不是* reactive *。看到我添加的筆記。爲了使其反應,我們需要做額外的工作。 – Bert

+0

@TonySherman我添加了一些代碼,它會使它*反應*但注意最後一句話。您越是依賴這家商店,您就越應該考慮使用Vuex。 – Bert