如何在Vue.js中新增或應用全域性變數?
在Vue.js應用程式中,可能有一些資料或工具在許多元件中使用,但您不想更改其作用域並保持其值對所有元件都相同。這些型別的變數稱為全域性變數。在這種情況下,使用者可以使用以下語法定義原型:
Vue.prototype.$appName = 'My App'
現在這個$appName將在所有Vue例項上可用,甚至在建立之前。在appName之前定義的$是用於所有例項都可用的屬性的約定。使用者還可以使用全域性mixin來影響Vue例項。您可以將資料新增到此mixin,使一個或多個值可用於所有Vue元件。
請檢視下面的示例以瞭解更多資訊。
示例
首先,我們需要建立一個Vue專案。要做到這一點,您可以參考此頁面。在您的Vue專案中建立兩個檔案app.js和index.html。下面給出了包含程式碼片段的檔案和目錄,用於這兩個檔案。將下面的程式碼片段複製並貼上到您的Vue專案中,然後執行Vue專案。您將在瀏覽器視窗中看到下面的輸出。
檔名 - app.js
目錄結構 -- $project/public -- app.js
// This is a global mixin, it is applied to every vue instance. // Mixins must be instantiated *before* your call to new Vue(...) Vue.mixin({ data: function() { return { get globalReadOnlyProperty() { return "This property cannot be changed !"; } } } }) Vue.component('child', { template: "<div>In Child: {{globalReadOnlyProperty}}</div>" }); new Vue({ el: '#app', created: function() { this.globalReadOnlyProperty = "I am a global read only Property"; } });
檔名 - index.html
目錄結構 -- $project/public -- index.html
<!DOCTYPE html> <html> <head> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> </head> <body> <div style="text-align: center;"> <h2> Add or apply global variables in Vue.js </h2> </div> <div id="app" style="text-align: center;"> In Root: {{globalReadOnlyProperty}} <child></child> </div> <script src='app.js'></script> </body> </html>
執行以下命令以獲得以下輸出:
C://my-project/ > npm run serve
完整的HTML程式碼
現在讓我們使用app.js和index.html檔案建立一個完整的程式碼。此程式碼可以作為HTML檔案執行。
<!DOCTYPE html> <html> <head> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> </head> <body> <div style="text-align: center;"> <h2> Add or apply global variables in Vue.js </h2> </div> <div id="app" style="text-align: center;"> In Root: {{globalReadOnlyProperty}} <child></child> </div> <script> // This is a global mixin, it is applied to every vue instance. // Mixins must be instantiated *before* your call to new Vue(...) Vue.mixin({ data: function() { return { get globalReadOnlyProperty() { return "This property cannot be changed !"; } } } }) Vue.component('child', { template: "<div>In Child: {{globalReadOnlyProperty}}</div>" }); new Vue({ el: '#app', created: function() { this.globalReadOnlyProperty = "I am a global read only Property"; } }); </script> </body> </html>
在本文中,我們討論了全域性變數以及如何在Vue.js中新增它們。我們建立了app.js和index.html檔案,並使用<script>標籤將app.js檔案新增到index.html檔案中。最後,我們透過將app.js和index.html組合成一個HTML檔案來建立完整的程式碼。
廣告