Vue2 原型鍊方法 - daniel-qa/Vue GitHub Wiki
Vue2 原型鍊方法
Vue.prototype.$integratedQuotaService = integratedQuotaService;
console.log('已將 integratedQuotaService 加入 Vue.prototype:', Vue.prototype.$integratedQuotaService);
這樣就能在 console 看到 service。
然後在任何元件裡:
export default {
mounted() {
console.log(this.$integratedQuotaService) // ✅ 可用
}
}
在設定的那個組件,要用 Vue.prototype.$xxx
在其他組件,就用 this.$xxx
// 把 integratedQuotaService 加入 prototype
Vue.prototype.integratedQuotaService = this.integratedQuotaService;
console.log('已將 integratedQuotaService 加入 Vue.prototype:', Vue.prototype.integratedQuotaService);
1. 基本示例
在main.js中添加一个变量到 Vue.prototype
Vue.prototype.$appName = 'My App'
这样 $appName 就在所有的 Vue 实例中可用了,甚至在实例被创建之前就可以
new Vue({
beforeCreate: function () {
console.log(this.$appName)
}
})
控制台会打印出 My App
2 .觀念說明
最佳實踐:放在 main.js 或初始化文件 → 保證全局可用
核心原則:要在組件創建之前就設置 Vue.prototype
- main.js 是 Vue 應用的入口點,主要用於全局注入,確保所有組件在創建前都能共享特定的方法或屬性。
這樣做的好處是能提供單一來源,避免程式碼分散,並增強可見性,讓開發者能一目了然地知道應用中有哪些全局資源。
- 需要局部的變數隔離的話,可以放在組件被創建前的 js,這樣,其他組件就取不到。
- 原型鏈原理
每個物件都有一個內部鏈接,指向它的原型(Prototype / proto)。
- 訪問屬性或方法時:
JS 先在自身物件找,找不到就沿著原型鏈向上查找,一層一層找,直到原型為 null 為止
- Vue.prototype 就是 Vue 實例的原型:
所有 Vue 組件實例都沿著這個鏈查找 $mindMapInfo
所以只要注入一次,就能被每個組件使用
- 視覺化比喻
this.$mindMapInfo
│
▼
Vue Instance
│
▼
Vue.prototype.$mindMapInfo ← 定義在這裡,所有實例都可用
│
▼
Object.prototype ← JS 內建方法
│
▼
null ← 原型鏈終點
💡 核心重點:
原型鏈就像「樹狀結構」,向上尋找屬性
Vue 利用原型鏈做全局方法/屬性注入
這也是 JS 物件導向的重要機制
Vue.prototype.$mindMapInfo = this
this.$mindMapInfo.變數或method
vue2超實用
你可以透過修改 Vue.prototype 來為所有 Vue 實例新增全域方法或屬性。這在開發插件或新增一些常用工具方法時非常有用。
// 範例:新增一個全域的工具方法
Vue.prototype.$myGlobalMethod = function (text) {
console.log('這是一個全域方法:', text);
};
const app = new Vue({
el: '#app',
mounted() {
// 這裡可以直接使用 $myGlobalMethod
this.$myGlobalMethod('透過原型鍊輕鬆使用!');
}
});
這樣一來,所有由 new Vue() 創建的實例都能直接存取 this.$myGlobalMethod,而不需要在每個元件中單獨引入或定義。
總結來說,Vue 2 的原型鍊機制是它實現核心功能的重要基石,它讓所有元件實例都能繼承並共用 Vue 的核心功能,同時也提供了一個方便的擴展點。