Vue組件之非單文件組件的使用詳解
標準化開發(fā)時的嵌套:
在實際開發(fā)中,通常會創(chuàng)建一個 APP 組件作為根組件,由這個根組件去管理其它的組件,而 Vue 實例只需要管理這個 APP 組件就行了。
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Vue2標準化開發(fā)時的嵌套</title> <script src="./js/vue.js"></script> </head> <body> <div id="APP"></div> <script> // 創(chuàng)建組件一 const FrameHead = { template: ` <div> <p>{{name}}</p> </div> `, data() { return { name:"組件一" } } } // 創(chuàng)建組件二 const FrameBody = { template: ` <div> <p>{{name}}</p> </div> `, data() { return { name:"組件二" } } } // 創(chuàng)建最大的根組件,由它來管理其它的組件 const app = { template: ` <div> <frame-head></frame-head> <frame-body></frame-body> </div> `, components:{ FrameHead, FrameBody } } const vm = new Vue({ template:`<app></app>`, el: "#APP", components: {app} }); </script> </body> </html>
VueComponent 構造函數(shù)【擴展】:
<div id="APP"> <my-code></my-code> </div>
const MyCode = Vue.extend({ template: ` <div> <p>{{name}}</p> </div> `, data() { return { name:"你好呀!" } } }) console.log(MyCode); // VueComponent const vm = new Vue({ el: "#APP", components: { MyCode } });
注:其實組件就是一個構造函數(shù) VueComponent 。
關于 VueComponent:
- 組件本質(zhì)是一個名為 VueComponent 的構造函數(shù),且不是程序員定義的,是 Vue.extend 自動生成的。
- 我們只要使用組件,Vue 解析時就會幫我們創(chuàng)建這個組件的實例對象,也就是 Vue 幫我們執(zhí)行了 new VueComponent(options) 這個構造函數(shù)。
- 特別注意:每次調(diào)用 Vue.extend,返回的都是一個全新的 VueComponent 。
- 組件中的 this 指向:data 函數(shù)、methods 中的函數(shù)、watch 中的函數(shù)、computed 中的函數(shù),它們的 this 均是【VueComponent 實例對象】。
- Vue 實例中的 this 指向:data 函數(shù)、methods 中的函數(shù)、watch 中的函數(shù)、computed 中的函數(shù),它們的 this 均是【Vue 實例對象】。
Vue 實例與 VueComponent 的內(nèi)置關系:
// 查看 VueComponent 和 Vue 實例的關系 console.log( MyCode.prototype.__proto__ === Vue.prototype ); // true
- 一個重要的內(nèi)置關系:VueComponent.prototype.__proto__ === Vue.prototype
為什么要有這個關系:讓組件實例對象 VueComponent 可以訪問到 Vue 原型上的屬性和方 法。
注:Vue 強制更改了 VueComponent 的原型對象指向 Object 的原型對象的隱式鏈,將其改到指向 Vue 的原型對象上。
到此這篇關于Vue組件之非單文件組件的使用詳解的文章就介紹到這了,更多相關Vue非單文件組件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
ElementUI級聯(lián)選擇器實現(xiàn)同一父級下最多只能選中一個子級
本文主要介紹了ElementUI級聯(lián)選擇器實現(xiàn)同一父級下最多只能選中一個子級,同一父級下的子節(jié)點單選,又可以選擇多個不同父級下的節(jié)點,具有一定參考價值,感興趣的可以了解一下2023-10-10在Vue3中使用vue3-print-nb實現(xiàn)前端打印功能
在前端開發(fā)中,經(jīng)常需要打印頁面的特定部分,比如客戶列表或商品詳情頁,要快速實現(xiàn)這些功能,可以使用 vue3-print-nb 插件,本文就給大家介紹了如何在 Vue 3 中使用 vue3-print-nb 實現(xiàn)靈活的前端打印,需要的朋友可以參考下2024-06-06在 Vue 3 中上傳 KML 文件并在地圖上顯示的實現(xiàn)方法
KML 文件作為一種標準的地理數(shù)據(jù)格式,廣泛應用于地理信息系統(tǒng)(GIS)中,通過 OpenLayers 和 Vue 3 的組合,您可以方便地實現(xiàn)地圖數(shù)據(jù)的可視化和交互,本文介紹在 Vue 3 中上傳 KML 文件并在地圖上顯示的實現(xiàn)方法,感興趣的朋友一起看看吧2024-12-12vue post application/x-www-form-urlencoded如何實現(xiàn)傳參
這篇文章主要介紹了vue post application/x-www-form-urlencoded如何實現(xiàn)傳參問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-04-04vue cli3 實現(xiàn)分環(huán)境打包的步驟
這篇文章主要介紹了vue cli3 實現(xiàn)分環(huán)境打包的步驟,本文通過圖文并茂的形式給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-03-03