1.組件的嵌套
組件嵌套:把組件與組件嵌套在一起,
在父組件下的模板中,以標簽的形式調用子組件。
2 . 組件通信
組件通信 : 就是把同一個信息可以在不同的組件中共用
方式一 : 組件 父傳子 用 Props 父組件將信息傳給子組件,從而子組件獲得父組件的信息
父組件和子組件,之間靠子組件標簽取得關聯,在子組件標簽上所有的屬性構成的集合在子組件的props屬性可以接受到。
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>組件-父傳子</title> <script type="text/javascript" src="js/vue.js"> </script> </head> <body> <div id="app"> <!-- 調用組件標簽 --> <heads></heads> </div> </body> </html> <template id="temp"> <!-- 創建模板 --> <div> <!-- 定義模板只能有一個頂層標簽 --> <h3>這是我的第一個模板</h3> <p>{{msg}}</p> <!-- 組件的數據放在模板里 --> <son :tab = "msg"></son> <!-- 組件標簽 :tab 綁定動態屬性 msg是數據 --> </div> </template> <script type="text/template" id="temp1"> <!-- 子組件的模板 --> <div> <h2>good moring {{tab}}</h2> <p>{{msg}} {{tab}}</p> </div> </script> <script type="text/javascript"> // 定義子組件 let Son = { template : "#temp1", // 每個組件都有一個props屬性,這個屬性是該組件的組件標簽身上所有屬性構成的集合 props : ["tab"], data : function (){ return { msg : "這是我的子組件", } }, mounted(){ this.tab = this.$props.tab; } } // 定義組件 let Heads = { // 組件名必須大寫,不能使用h5標簽 template : "#temp", // 模板和組件通過id相關聯 data : function (){ // 組件的data是一個函數 return{ msg : "hello Miss wang!", } }, components : { son : Son, // 注冊子組件 } } // app是最大的根組件 let app = new Vue({ el : "#app", data : {}, components : { heads : Heads, // 注冊組件 } }); </script>
方式二 : 組件 父取到子的信息(即 子傳父)
refs 是組件模板下,所有子組件標簽構成的集合。
1. 在子組件的標簽上添加 ref 屬性
2.在父組件下使用this.$refs 就可以看到子組件標簽的所有信息
方式三 : 自定義事件--子傳父
人為觸發的事件,創建的方法是this.$emit
1. 在子組件的模板中添加事件名與事件方法(注意事件名與事件方法),在對應的組件模板中用$emit定義事件
$emit定義事件
2. 在子組件標簽下 用v-on 或 @ 去接受自定義的事件
3.寫事件方法
實例 : 自定義事件
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>自定義組件-子傳父</title> <script type="text/javascript" src="js/vue.js"> </script> </head> <body> <div id="app"> <!-- 調用組件標簽 --> <heads></heads> </div> </body> </html> <template id="temp"> <!-- 創建模板 --> <div> <!-- 定義模板只能有一個頂層標簽 --> <h3>這是我的第一個模板</h3> <p>{{msg}}</p> <!-- 組件的數據放在模板里 --> <son @switch = "dd"></son> <!-- 接受事件 --> </div> </template> <script type="text/template" id="temp1"> <!-- 子組件的模板 --> <div> <h2>good moring</h2> <p>{{msg}}</p> <button @click = "ff">點擊提交</button> </div> </script> <script type="text/javascript"> // 定義子組件 let Son = { template : "#temp1", data : function (){ return { msg : "這是我的子組件", } }, methods : { ff : function(){ // 定義一個事件 $emit("事件名",數據) this.$emit("switch",this.msg); } }, } // 定義組件 let Heads = { // 組件名必須大寫,不能使用h5標簽 template : "#temp", // 模板和組件通過id相關聯 data : function (){ // 組件的data是一個函數 return{ msg : "hello Miss wang!", } }, methods : { dd : function(res){ this.msg = res; } }, components : { son : Son, // 注冊子組件 } } // app是最大的根組件 let app = new Vue({ el : "#app", data : { }, components : { heads : Heads, // 注冊組件 } }); </script>