1、父組件
const cnp2 = Vue.extend({ template: ` <div> <h2>我是構造器2</h2> <cpn1></cpn1> </div> `, components: { cpn1: cnp1 } })
2、子組件
const cnp1 = Vue.extend({ template: ` <div> <h2>我是構造器1</h2> </div> ` })
解析:父組件和子組件的區分和形成。
當組件存在這種關系的時候,就存在父子關系--------當一個組件在另一個組件中注冊,這時候,被注冊的組件是子組件,包含着子組件的就是父組件
*****完整代碼****
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script src="../js/vue.js"></script> </head> <div id="app"> <cpn2></cpn2> </div> <body> <script> const cnp1 = Vue.extend({ template: ` <div> <h2>我是構造器1</h2> </div> ` }) const cnp2 = Vue.extend({ template: ` <div> <h2>我是構造器2</h2> <cpn1></cpn1> </div> `, components: { cpn1: cnp1 } }) let vm = new Vue({ el: '#app', data: () => ({}), components: { cpn2: cnp2 } }) </script> </body> </html>
3、全局組件和局部組件的語法糖寫法
優點:省去Vue.extend()的這種寫法,直接用一個對象代替
1、全局組件語法糖
Vue.component('mycpn', { template: ` <h2>全局組件,語法糖寫法</h2> ` })
2、局部組件語法糖
components: { mycpn: { template: ` <h2>局部組件,語法糖寫法</h2> ` } }
*****完整代碼****
<html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script src="../js/vue.js"></script> </head> <div id="app"> <mycpn /> </div> <div id="app2"> <mycpn /> </div> <body> <script> Vue.component('mycpn', { template: ` <h2>全局組件,語法糖寫法</h2> ` }) let vm = new Vue({ el: '#app', components: { mycpn: { template: ` <h2>局部組件,語法糖寫法</h2> ` } }, }) let vm2 = new Vue({ el: '#app2' }) </script> </body> </html>