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 構(gòu)造函數(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
}
});注:其實組件就是一個構(gòu)造函數(shù) VueComponent 。

關(guān)于 VueComponent:
- 組件本質(zhì)是一個名為 VueComponent 的構(gòu)造函數(shù),且不是程序員定義的,是 Vue.extend 自動生成的。
- 我們只要使用組件,Vue 解析時就會幫我們創(chuàng)建這個組件的實例對象,也就是 Vue 幫我們執(zhí)行了 new VueComponent(options) 這個構(gòu)造函數(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)置關(guān)系:
// 查看 VueComponent 和 Vue 實例的關(guān)系 console.log( MyCode.prototype.__proto__ === Vue.prototype ); // true

- 一個重要的內(nèi)置關(guān)系:VueComponent.prototype.__proto__ === Vue.prototype
為什么要有這個關(guān)系:讓組件實例對象 VueComponent 可以訪問到 Vue 原型上的屬性和方 法。

注:Vue 強制更改了 VueComponent 的原型對象指向 Object 的原型對象的隱式鏈,將其改到指向 Vue 的原型對象上。
到此這篇關(guān)于Vue組件之非單文件組件的使用詳解的文章就介紹到這了,更多相關(guān)Vue非單文件組件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue封裝可復用組件confirm,并綁定在vue原型上的示例
今天小編就為大家分享一篇vue封裝可復用組件confirm,并綁定在vue原型上的示例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-10-10
Vue 中使用lodash對事件進行防抖和節(jié)流操作
這篇文章主要介紹了Vue 中使用lodash對事件進行防抖和節(jié)流操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-07-07
vue實現(xiàn)動態(tài)路由的方法及路由原理解析
這篇文章主要介紹了路由原理及vue實現(xiàn)動態(tài)路由,Vue Router 提供了豐富的 API,可以輕松地實現(xiàn)路由功能,并支持路由參數(shù)、查詢參數(shù)、命名路由、嵌套路由等功能,可以滿足不同應(yīng)用程序的需求,需要的朋友可以參考下2023-06-06
element ui提交表單返回成功后自動清空表單的值的實現(xiàn)代碼
這篇文章主要介紹了elementui提交表單返回成功后自動清空表單的值,本文通過兩種方法結(jié)合實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-08-08

